Golang Standards for Scalable and Maintainable Code

Author

Reads 1K

Woman in focus working on software development remotely on laptop indoors.
Credit: pexels.com, Woman in focus working on software development remotely on laptop indoors.

Golang encourages developers to write clean and readable code by following the Go Standard Library. This library provides a set of guidelines for coding in Go, including rules for naming conventions, error handling, and code organization.

The Go Standard Library recommends using lowercase letters with words separated by underscores for package names, such as "math" or "net/http". This convention makes code easier to read and understand.

Following the Go Standard Library guidelines helps to write maintainable code that is easy to understand and modify. By using the recommended naming conventions and code organization, developers can reduce the time and effort required for code maintenance and updates.

A fresh viewpoint: Go vs Golang

Project Structure

Project Structure is crucial in Go development, and following the standardized guidelines is a must. The Go team provides additional guidance on package names, which is essential for creating a well-structured project.

A package's name should provide context for its contents, making it easier for clients to understand what the package is for and how to use it. This is in line with the Go philosophy of naming packages that signify what they contain.

A fresh viewpoint: Golang Go

Credit: youtube.com, The BEST Tool to Structure Golang Projects

Don't use the pkg pattern, as it goes against the Go philosophy. The pkg directory was used in the past but was later removed.

The same goes for util or misc packages - they're not recommended. Instead, break out related utility functionalities into their own package or integrate them into the original package if they're not widely used.

Having too many small packages with only one file is a sign of poor package organization. This usually indicates that the packages haven't been thought through properly. Look at the API boundaries and group the packages into bigger chunks.

Here are some anti-patterns to keep in mind:

  • Don't use the pkg pattern.
  • Avoid util or misc packages.
  • Avoid having too many small packages.

Expand your knowledge: Salesforce Native App

Coding Standards

In Go, coding standards are crucial for maintaining a clean and organized codebase.

The official Go style guide recommends using lowercase letters with words separated by underscores for package names, such as "math/rand".

Go's coding standards also emphasize the importance of concise and readable code, with a maximum line length of 80 characters.

Credit: youtube.com, Linus's Laws of Writing Readable Code

The use of blank lines to separate logical sections of code is encouraged, making it easier to scan and understand the code.

Consistent naming conventions, such as using camelCase for function and variable names, help to avoid confusion and make the code more readable.

The Go community places a strong emphasis on following these coding standards to ensure that Go code is maintainable and efficient.

Error Handling

Error handling is a crucial aspect of Go programming. It's essential to return errors instead of boolean values for ID validation errors, as this provides more information to the user about why the object is invalid.

The Go standard library recommends using the error type for exported functions that return errors. This is because concrete error types can be susceptible to subtle bugs, such as a nil pointer getting wrapped into an interface.

Error strings should not be capitalized, unless beginning with an exported name, a proper noun, or an acronym. This is because error strings often appear within other context before being printed to the user.

Credit: youtube.com, The secret to making Golang error handling a breeze

A library writer is free to implement the error interface with a richer model under the covers, making it possible not only to see the error but also to provide some context. For example, os.Open returns an error value that describes what went wrong, including the problematic file name, the operation, and the operating system error it triggered.

Here are some best practices for error handling:

  • Return errors instead of boolean values for ID validation errors.
  • Use the error type for exported functions that return errors.
  • Avoid capitalizing error strings, unless necessary.
  • Provide detailed error information using the error interface.
  • Use type assertions or type switches to look for specific errors and extract details.

By following these guidelines, you can write more robust and informative error handling code in Go.

Logging

Log messages should be annotated with contextual information in the form of key-value pairs to make it easier to identify the context they originated from. This is achieved by using snake_case for key names, which can be referenced in the corresponding JSON struct tags.

Contextual information is crucial in logging, as it helps administrators quickly understand what's happening in the application. By including relevant details, log messages become more meaningful and concise.

Credit: youtube.com, Go Structured Logging with the slog Package (Golang)

For example, critical log lines should represent the most severe situations, such as a server startup routine failing, resulting in the service terminating. This is a situation where immediate action is required.

Error log lines, on the other hand, indicate unexpected issues that don't result in a total loss of service. These should be actionable, allowing administrators to investigate and resolve the incident.

Performance

Performance is a crucial aspect of any codebase, and Go is no exception. Any PR that can potentially have a performance impact on the mattermost/server codebase is encouraged to have a performance review.

New features that require benchmarks or have missing load-test coverage should be thoroughly reviewed. This ensures that they don't inadvertently slow down the system.

PRs touching performance of critical parts of the codebase, such as Hub/WebConn, should also be scrutinized. This includes any changes to SQL queries, which can have a significant impact on performance.

Credit: youtube.com, Rust vs. Go (Golang): Performance (Only Standard Library)

Creating goroutines, doing potentially expensive allocations, and using recursion, unbounded loops, or deeply nested for loops can all impact performance. Be mindful of these when coding.

Regular expressions, especially when creating regexp.MustCompile dynamically every time, can also be performance-intensive. Use them sparingly.

Here are some specific areas to watch out for:

  • New features requiring benchmarks or load-test coverage
  • PRs touching performance of critical parts of the codebase (e.g. Hub/WebConn)
  • PRs adding or updating SQL queries
  • Creating goroutines
  • Doing potentially expensive allocations: bytes.Buffer and []byte
  • Recursion, unbounded, and deeply nested for loops
  • Use of locks and/or other synchronization primitives
  • Regular expressions, especially when creating regexp.MustCompile dynamically every time
  • Use of the reflect package

Testing

In Go, it's essential to follow best practices for testing to ensure your code is robust and maintainable.

You should avoid using string comparison to check error messages, as this can make your tests brittle and prone to breaking with future changes. Instead, use functions like errors.Is or cmp with cmpopts.EquateErrors to check for semantic information.

When writing unit tests, it's common to only care whether an error occurred or not, in which case you can simply test if the error was non-nil. If you need to test that the error semantically matches some other error, consider using errors.Is.

Test helpers are functions that perform setup or cleanup tasks, and all failures that occur in them are expected to be failures of the environment, not from the code under test. If you pass a *testing.T, call t.Helper to attribute failures in the test helper to the line where the helper is called.

Readers also liked: Golang Check Type

Credit: youtube.com, GopherCon 2017: Advanced Testing with Go - Mitchell Hashimoto

Tests in the same package can access unexported identifiers, enabling better test coverage and more concise tests. However, be aware that any examples declared in the test will not have the package names that a user will need in their code.

The Go standard library provides the testing package, which is the only permitted testing framework for Go code in the Google codebase. This package provides a minimal but complete set of functionality for writing good tests, including top-level tests, benchmarks, runnable examples, subtests, logging, failures, and fatal failures.

To write a test in the same package as the code being tested, place the tests in a foo_test.go file, use package foo for the test file, and do not explicitly import the package to be tested.

Code Style

In Go, we use CamelCase names for variables and constants. This means using a single word or a combination of words with the first letter capitalized, like WebsocketEventPostEdited.

Credit: youtube.com, The 3 Laws of Writing Readable Code

For instance, you should use WebsocketEventPostEdited instead of WEBSOCKET_EVENT_POST_EDITED. This style is consistent throughout the codebase.

When writing comments, it's a good idea to use doc preview during development and code review to see how the documentation and examples will be presented. This helps ensure that the documentation is useful and easy to read.

Take a look at this: Golang Use Cases

Camel Case Variables/Constants

In CamelCase, variable and constant names should be written in a single word with each new word starting with a capital letter, like WebsocketEventPostEdited.

This style is preferred over using underscores or other separators, such as WEBSOCKET_EVENT_POST_EDITED.

Initialisms

Initialisms are a common occurrence in coding, and it's essential to get them right. In names with multiple initialisms, each letter within a given initialism should have the same case, but each initialism in the name doesn't need to have the same case.

For instance, in XMLAPI, XML and API are both initialisms, but they can be written in different cases. XMLAPI is a common convention, but xmlAPI is also acceptable.

Two professionals collaborating on software development in a modern indoor setting.
Credit: pexels.com, Two professionals collaborating on software development in a modern indoor setting.

In names with an initialism containing a lowercase letter, the initialism should appear as it would in standard prose. For example, DDoS, iOS, and gRPC are all written in lowercase in standard English usage. However, if you need to change the first letter for the sake of exportedness, the entire initialism should be the same case.

Here's a breakdown of correct and incorrect examples:

Comment Line Length

Comment Line Length is a key aspect of readable code. Ensure that commentary is readable from source even on narrow screens.

The goal is to keep comments concise, with a recommended line length of 80 columns. However, this is not a hard and fast rule, and there's no fixed limit for comments in Go.

The standard library often breaks comments based on punctuation, which can result in lines closer to 60-70 characters. This approach is acceptable, but it's not a justification to change existing code that exceeds 80 characters.

Avoid comments that will wrap repeatedly on small screens, as this can be a poor reader experience.

Code Style

Credit: youtube.com, Should I trust this code style guide?

Indentation is key when using doc preview during development and code review, as lists and code snippets should usually be indented to avoid linewrapping.

Godoc uses very little special formatting, so it's best to keep things simple and avoid decoration. This makes it easier for others to read and understand your code.

For doc comments, all top-level exported names must have them, as should unexported type or function declarations with unobvious behavior or meaning. These comments should be full sentences that begin with the name of the object being described.

A good rule of thumb is to write doc comments as if anyone using the package will be reading them, which means making them clear and concise.

If you have doc comments for unexported code, follow the same custom as if it were exported, starting the comment with the unexported name. This makes it easy to export it later by simply replacing the unexported name with the newly-exported one across both comments and code.

Recommended read: Golang Source Code

Credit: youtube.com, L04 Code Style for Humans

Documentation comments should always be complete sentences, and as such should always be capitalized and punctuated.

Comments that are sentence fragments have no such requirements for punctuation or capitalization, but documentation comments are always complete sentences.

Here are some tips for writing good comments:

  • Use complete sentences for documentation comments
  • Avoid decoration and keep things simple
  • Indent lists and code snippets to avoid linewrapping

Go provides C-style /* */ block comments and C++-style // line comments. Line comments are the norm, but block comments appear mostly as package comments, and are useful within an expression or to disable large swaths of code.

Comments that appear before top-level declarations, with no intervening newlines, are considered to document the declaration itself.

Curious to learn more? Check out: Golang Line

Examples

Examples are a crucial part of documenting your code. They should clearly show how to use a package or function.

Runnable examples belong in the test file, not the production source file. This is because they are meant to be executed and tested.

If a runnable example isn't feasible, you can still provide example code within code comments. This code should follow standard formatting conventions.

CSS code displayed on a computer screen highlighting programming concepts and technology.
Credit: pexels.com, CSS code displayed on a computer screen highlighting programming concepts and technology.

Types can often be clearer than names in function signatures. This is demonstrated by the example in GoTip #38, which shows how functions can be used as named types.

Best practice suggests that if a function or variable is non-trivial, it should be tested directly, independently of any tests that use it.

Importing

Importing in Go follows some specific guidelines to maintain control over dependencies and make testing easier. You can import packages only for their side effects using the syntax `import _ "package"`, but this is only allowed in main packages or tests.

Some examples of packages that can be imported this way include `time/tzdata` and `image/jpeg` in image processing code. Avoid using blank imports in library packages, even if the library indirectly depends on them.

You can use a blank import to bypass the check for disallowed imports in the nogo static checker, or to import the `embed` package in a source file that uses the `//go:embed` compiler directive. If you create a library package that indirectly depends on a side-effect import in production, document the intended usage.

Import Renaming

Credit: youtube.com, Tebeka Shorts: Renaming Imports - For Code Clarity

Import Renaming is a necessary evil in coding, especially when you have to work with packages that have common variable names.

Package imports shouldn't normally be renamed, but sometimes it's unavoidable, especially when there's a name collision with other imports.

You should rename an imported package to avoid a name collision with other imports. If you're lucky, good package names won't require renaming.

Generated protocol buffer packages must be renamed to remove underscores from their names, and their local names must have a pb suffix. This is a specific case where renaming is required.

You can also rename an imported package if it has an uninformative name, like 'util' or 'v1'. However, do this sparingly, as it's better to refactor the package itself with a more suitable name.

If you need to import a package whose name collides with a common local variable name, the preferred way to do so is with the pkg suffix. For example, 'urlpkg' instead of just 'url'.

For another approach, see: T Golang

Import Blank (Import _)

A blank spiral notebook on a wooden table surrounded by dried leaves, perfect for design mock-ups.
Credit: pexels.com, A blank spiral notebook on a wooden table surrounded by dried leaves, perfect for design mock-ups.

Import Blank (Import _) is a useful tool in Go programming. It allows you to import packages for their side effects, which can be useful in certain situations.

You can use a blank import to bypass the check for disallowed imports in the nogo static checker. This is one of the exceptions to the rule that side-effect imports should only be used in main packages or tests.

The following packages are examples of side-effect imports that you might use with a blank import: time/tzdata and image/jpeg in image processing code.

You can also use a blank import to silence complaints about unused imports and variables. This can be helpful when you're still developing a program and you're not sure if certain imports or variables will be needed later.

Assigning an unused variable to the blank identifier will silence the unused variable error. By convention, you should put these global declarations right after the imports and comment them, both to make them easy to find and as a reminder to clean things up later.

Here are some examples of when you might use a blank import to silence complaints:

  • Unused imports: fmt and io
  • Unused variable: fd

Note that you should avoid using blank imports in library packages, even if the library indirectly depends on them.

Functions

Credit: youtube.com, Go (Golang) Tutorial #9 - Using Functions

Functions in Go should have their signature on a single line to avoid indentation confusion. This makes it easier to read and understand the code.

Function argument lists can be long and unwieldy, but it's better to break them up using local variables or option structs rather than adding inline comments. Inline comments can clutter the code and make it harder to read.

Long string literals within functions should not be broken up for the sake of line length, but rather after the string format, with arguments provided on subsequent lines. This approach makes the code more readable and easier to understand.

A different take: Golang Os Read File

Cmd

Writing your code in a function, or "cmd", can be a great way to organize your program. You want to put your code in places where it belongs.

Knowing your layout and what you're trying to achieve is key to avoiding code that doesn't belong. This makes refactoring easier.

Writing the obvious code first and then refactoring is a good approach. It helps you avoid making too many assumptions about what your program could do.

Public vs Private

Credit: youtube.com, Asymmetric Encryption - Simply explained

In Go, public variables and functions start with a capital letter, making them accessible outside your package. This is a key distinction from private variables and functions, which start with a lowercase letter and cannot be accessed outside your package.

Public variables and functions are the default choice, as they offer flexibility and avoid misleading compiler warnings. If you can't say why something needs to be private, it's better to make it public.

A public variable or function can be accessed from anywhere, which is useful for shared data or functionality. But beware of the compiler's warnings, which can be tough to decipher, especially for beginners.

Functions

Functions are an essential part of any Go program, and naming them correctly is crucial for readability and maintainability.

Function and method names should not use a Get or get prefix, unless the underlying concept uses the word “get” (e.g. an HTTP GET). This is because starting the name with the noun directly makes it easier to understand the purpose of the function.

Credit: youtube.com, FUNCTIONS - Top 10 Must Knows About Functions

For example, instead of GetCounts, use Counts. This simple change can make a big difference in the clarity of your code.

Go doesn't provide automatic support for getters and setters, so you'll need to provide them yourself. A getter method should be named after the field it's accessing, with the first letter capitalized (e.g. Owner).

A setter function, if needed, will likely be called SetOwner. Both names read well in practice and make it clear what the function is doing.

Must functions are used to stop the program on failure and should follow the naming convention MustXYZ (or mustXYZ). They're often used to initialize package-level variables or in test helpers that only stop the current test.

Must functions should not be called in places where it's difficult to ensure an error would be caught or in a context where an error should be checked. Instead, they should be used in a "value" context, such as in tests where you want to easily ensure that the Must arguments are well-formed.

Identify the Function

Colorful lines of code on a computer screen showcasing programming and technology focus.
Credit: pexels.com, Colorful lines of code on a computer screen showcasing programming and technology focus.

In most tests, failure messages should include the name of the function that failed. This might seem obvious, but it's essential to include the function name in the failure message.

Specifically, your failure message should be in the format "YourFunc(%v) = %v, want %v" instead of just "got %v, want %v". This helps identify the function that caused the failure.

Including the function name in the failure message makes it easier to diagnose and fix the issue. It's like having a clear signpost that points to the problem.

Here are some examples of good and bad failure messages:

By including the function name in the failure message, you can quickly identify the source of the problem and fix it.

Multiple Return Values

Functions can return multiple values, which is a unique feature in Go. This allows for more clarity and simplicity in code.

One way to use multiple return values is to return a count and an error, as seen in the Write method from package os. This is a common style, and it's a great way to handle errors and return values at the same time.

Credit: youtube.com, How to Return Multiple Values from Functions | Golang Tutorial |

Returning multiple values can also obviate the need to pass a pointer to a return value to simulate a reference parameter. For example, a function can return a number and the next position in a byte slice.

This approach makes code shorter and clearer, and it's a good way to document what the function is doing. By naming the result parameters, you can make it obvious which returned value is which.

Function Formatting

Function formatting is crucial to maintain readability and avoid confusion. The signature of a function or method declaration should remain on a single line to avoid indentation confusion.

Long function argument lists can make some of the longest lines in a Go source file, but they precede a change in indentation, making it difficult to break the line without making subsequent lines look confusing.

To shorten lines, factoring out local variables is a good option. This can help reduce the number of arguments and make the code easier to read.

Credit: youtube.com, Strings -Display and Formatting, Print and Format Functions

Function and method calls should not be separated based solely on line length. If the API cannot be changed or if the local call is unusual, it's permissible to add line breaks to aid in understanding the call.

Avoid adding inline comments to specific function arguments where possible. Instead, use an option struct or add more detail to the function documentation.

Constructors and Composite Literals

Constructors and composite literals can simplify code by creating a new instance each time they are evaluated. This is especially useful when the zero value isn't good enough.

In Go, you can use composite literals to create new instances of structs, arrays, slices, and maps. The fields of a composite literal are laid out in order and must all be present, but you can label the elements explicitly as field:value pairs to make the initializers appear in any order.

Taking the address of a local variable is perfectly OK in Go, and it's even possible to return the address of a composite literal, which allocates a fresh instance each time it is evaluated. This means you can combine multiple lines of code into a single expression.

For another approach, see: Golang Time since

Credit: youtube.com, Golang Composite Literal

By labeling the elements explicitly as field:value pairs, you can make the initializers appear in any order, with the missing ones left as their respective zero values. For example, if you have a struct with fields A, B, and C, you can initialize only A and C, and the value of B will be its zero value.

A limiting case of composite literals is when they contain no fields at all, in which case they create a zero value for the type. This means you can use composite literals to create zero values for structs, arrays, slices, and maps.

Composite literals can also be used to create arrays, slices, and maps, with the field labels being indices or map keys as appropriate. The initializations work regardless of the values of Enone, Eio, and Einval, as long as they are distinct.

Here's an interesting read: Golang Create File

Variables and Types

Variables in Go should be named according to their scope, with longer names for larger scopes and shorter names for smaller scopes. A good rule of thumb is to keep variable names concise while still being clear and readable.

Credit: youtube.com, Golang - Variables

A variable's name should reflect what it contains and how it is being used in the current context, rather than where the value originated. Single-word names like "count" or "options" are a good starting point, and additional words can be added to disambiguate similar names.

Here are some guidelines for naming variables:

  • Single-word names like "count" or "options" are a good starting point.
  • Additional words can be added to disambiguate similar names, for example "userCount" and "projectCount".
  • Do not simply drop letters to save typing; for example, "Sandbox" is preferred over "Sbx".
  • Omit types and type-like words from most variable names.
  • Omit words that are clear from the surrounding context.

Constant

Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions.

In Go, constants can only be numbers, characters (runes), strings, or booleans. This means you can't define a constant that depends on a function call, like math.Sin(math.Pi/4), because the function call needs to happen at runtime.

Constant names must use MixedCaps, just like all other names in Go. This means exported constants start with uppercase and unexported constants start with lowercase.

Constant names should explain what the value denotes, not be a derivative of their values. For example, instead of naming a constant "PI_VALUE", you could name it "Pi" or "MathematicalConstantForPi".

Credit: youtube.com, Coding Basics: Variables | Programming for Beginners |

Name constants based on their role, not their values. If a constant doesn't have a role apart from its value, then it's unnecessary to define it as a constant.

You can create enumerated constants using the iota enumerator, which can be part of an expression and expressions can be implicitly repeated.

Variable

Variables are a crucial part of any programming language, and Go is no exception. A variable created at file scope may require multiple words, whereas a variable scoped to a single inner block may be a single word or even just a character or two, to keep the code clear and avoid extraneous information.

The general rule of thumb is that the length of a name should be proportional to the size of its scope and inversely proportional to the number of times that it is used within that scope. This means that a variable with a small scope, such as one or two small operations performed in 1-7 lines, can have a short name, while a variable with a larger scope may require a longer name.

Asian man in white shirt focused on coding at modern office workspace.
Credit: pexels.com, Asian man in white shirt focused on coding at modern office workspace.

Single-word names like count or options are a good starting point for variable names. Additional words can be added to disambiguate similar names, for example userCount and projectCount.

Variables can be initialized just like constants, but the initializer can be a general expression computed at run time. This means that variables can be assigned a value that is calculated on the fly, rather than being a fixed value.

Single-letter variable names can be a useful tool to minimize repetition, but can also make code needlessly opaque. Limit their use to instances where the full word is obvious and where it would be repetitive for it to appear in place of the single-letter variable. For example, using a single-letter name like i for an integer loop variable is acceptable, but using a single-letter name like s for a string variable may not be as clear.

Here are some guidelines for when to use single-letter variable names:

  • For a method receiver variable, a one-letter or two-letter name is preferred.
  • Using familiar variable names for common types is often helpful:
  • Single-letter identifiers are acceptable as integer loop variables, particularly for indices (e.g., i) and coordinates (e.g., x and y).
  • Abbreviations can be acceptable loop identifiers when the scope is short, for example for _, n := range nodes { ... }.

Nil Slices

Credit: youtube.com, Go Class: 10 Slices in Detail

Nil slices are often misunderstood, but fortunately, most built-in functions behave as expected on them.

For most purposes, there is no functional difference between nil and the empty slice. Len and cap behave as expected on nil slices.

Declaring an empty slice as a local variable can lead to bugs if it's a return value, so it's better to prefer nil initialization.

Nil slices should not be used to force clients to make distinctions between nil and empty slices, as this can lead to programming errors.

Using len to check for emptiness is a good way to avoid making a distinction between a nil slice and a non-nil, zero-length slice.

This approach is typically used in well-designed APIs, which often employ nil slices to enhance readability.

Pointers vs Values

When deciding whether to use a pointer or value as a method receiver, it's essential to consider the implications of each choice.

Correctness should always take precedence over speed or simplicity. In some cases, you must use a pointer value, while in others, a value will suffice.

Credit: youtube.com, you will never ask about pointers again after watching this video

If the receiver is a slice and the method doesn't reslice or reallocate the slice, use a value rather than a pointer. For example, a method that returns the length of a buffer should use a value receiver.

If the method needs to mutate the receiver, the receiver must be a pointer. This is because a pointer method can modify the receiver, and invoking it on a value would cause the method to receive a copy of the value, so any modifications would be discarded.

If the receiver is a struct containing fields that cannot safely be copied, use a pointer receiver. This includes synchronization types like sync.Mutex.

Here's a summary of the key points to consider:

Type Switch

A type switch can be used to discover the dynamic type of an interface variable.

It uses the syntax of a type assertion with the keyword type inside the parentheses.

In a type switch, you can declare a variable in the expression, and the variable will have the corresponding type in each clause.

It's idiomatic to reuse the name in such cases, effectively declaring a new variable with the same name but a different type in each case.

If this caught your attention, see: Fallthrough Golang

Platform

Credit: youtube.com, TYPES OF VARIABLE

In the platform folder, you'll find all the platform-level logic that builds the actual product, like setting up the database, Redis instance, or a router.

This folder is separate from the app and cmd folders, and its packages don't care what's inside them.

The platform folder contains the necessary setup for the product, which is crucial for its functionality.

Packages inside this folder are designed to be independent of the app and cmd folders, allowing for a more modular and maintainable structure.

By keeping the platform logic separate, developers can easily manage and update the product's core components without affecting the app or cmd folders.

Crypto Rand

Crypto Rand is a reliable way to generate keys, even for throwaway ones. The package math/rand should be avoided because its generator is completely predictable if unseeded.

Using time.Nanoseconds() as a seed only adds a few bits of entropy, making it unreliable. The crypto/rand's Reader is a better choice for generating keys.

Printing the output from crypto/rand's Reader to hexadecimal or base64 is a good way to represent the generated keys as text. This makes it easier to work with the keys in different contexts.

Control Flow

Credit: youtube.com, Understanding Control Flow #golang

Go's control flow is a bit different from what you might be used to, especially if you're coming from a C or Java background. There's no do or while loop in Go, only a slightly generalized for loop.

The for loop is where things get interesting, as it can now accept an optional initialization statement, just like if and switch statements. This makes it a bit more flexible and powerful.

Switch statements in Go are also more flexible, with the ability to evaluate expressions that aren't just constants or integers. They're also evaluated top to bottom until a match is found, which makes them a great alternative to if-else-if-else chains.

One thing to keep in mind when using switch statements is that they automatically break, so you don't need to use a break statement at the end of each clause. Unless, of course, you want to achieve the C-style behavior, in which case you'll need to use a fallthrough statement.

It's also worth noting that using a break statement within a switch clause doesn't exit the enclosing for loop, unless you use a label on the for statement. This can be a bit tricky, so make sure to keep an eye out for it.

Goroutine Lifetimes

Credit: youtube.com, Advanced Golang: Limiting Goroutines

Goroutine lifetimes are crucial to understand, as they can easily get out of hand if not managed properly. Goroutines can leak by blocking on channel sends or receives, making it difficult for the garbage collector to terminate them.

Leaving goroutines in-flight when they're no longer needed can cause problems like data races and unpredictable memory usage. This is because modifying still-in-use inputs after the result isn't needed can lead to data races.

In Go, code that follows best practices around context usage often helps make goroutine lifetimes clear. This is conventionally managed with a context.Context.

A good rule of thumb is to keep synchronization-related code constrained within the scope of a function and factor out the logic into synchronous functions. If the concurrency is still not obvious, it's essential to document when and why the goroutines exit.

Here are some key takeaways to keep in mind:

  • The garbage collector will not terminate a goroutine blocked on a channel even if no other goroutine has a reference to the channel.
  • Leaving goroutines in-flight for arbitrarily long can lead to unpredictable memory usage.
  • Sending on a channel that has been closed causes a panic.

In general, it's essential to know how a goroutine will stop before starting it. This can be achieved by using channels, synchronization variables, or condition variables to signal completion.

Defer

Credit: youtube.com, Golang Tutorial for Beginners - Flow Control Statement - Advanced Use Cases of defer

Defer is a statement in Go that schedules a function call to be run immediately before the function executing the defer returns. This is an effective way to deal with situations where resources must be released regardless of which path a function takes to return.

The canonical examples of using defer are unlocking a mutex or closing a file. Deferring a call to a function like Close guarantees that you will never forget to close the file, which is easy to forget if you later edit the function to add a new return path.

Deferring a call to a function has two advantages: it ensures the resource is released, and it keeps the code organized by placing the close near the open. This is much clearer than placing it at the end of the function.

Deferred functions are executed in Last-In-First-Out (LIFO) order. This means that if you have multiple deferred function calls, they will be executed in the reverse order they were called.

The arguments to the deferred function are evaluated when the defer executes, not when the call executes. This means that a single deferred call site can defer multiple function executions.

Switch

Programming Codes Screengrab
Credit: pexels.com, Programming Codes Screengrab

Go's switch is more general than C's, allowing expressions that aren't constants or even integers.

The cases in a switch are evaluated top to bottom until a match is found, and if the switch has no expression, it switches on true.

It's possible to write an if-else-if-else chain as a switch, and this is even idiomatic in Go.

There is no automatic fall through in Go's switch, but cases can be presented in comma-separated lists.

Break statements can be used to terminate a switch early, but you'll need to use a label if you want to break out of a surrounding loop.

The continue statement also accepts an optional label, but it only applies to loops.

A switch can also be used to discover the dynamic type of an interface variable, using the syntax of a type assertion with the keyword type inside the parentheses.

If the switch declares a variable in the expression, the variable will have the corresponding type in each clause, and it's idiomatic to reuse the name in such cases.

Check this out: Golang Types

Katrina Sanford

Writer

Katrina Sanford is a seasoned writer with a knack for crafting compelling content on a wide range of topics. Her expertise spans the realm of important issues, where she delves into thought-provoking subjects that resonate with readers. Her ability to distill complex concepts into engaging narratives has earned her a reputation as a versatile and reliable writer.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.