Common Mistakes that should be avoided while coding in Golang

To code effectively in Golang, steer clear of common mistakes.

PRATHEESH PC
5 min readApr 3, 2023

Go is designed to be easy to use yet powerful enough to build complex applications with minimal code. However, coding in Go can be tricky since the language has some unique features that may cause developers to make mistakes if they are not careful.

Mistakes To Avoid is shown on a conceptual photo using wooden blocks Free Photo

Ignoring error returns from functions / methods

As we know, Golang doesn’t have an inbuilt try-catch exception handling. Instead it use error values and error returns from functions/methods to handle the exceptional situations.

Ignoring error returns from functions or methods can lead to runtime errors and unexpected behavior. Many functions in the Go standard library return an error value that indicates whether the operation was successful or not. If you ignore these error values, you may end up with unexpected results and your program may even crash at runtime.

func someDBOperation(user *models.User) (bool, error) {
}

It is common for functions/methods to use that may encounter an error to return an error value as their last return argument.

Ignoring the errors

It is essential to check for errors and handle them appropriately to avoid unexpected crashes.

In Go, the usual method to handle errors is to compare the given error to nil. A nil value indicates that no error happened, while a non-nil value indicates that an error occurred.

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorf("An error happened while erading the response body")
return err
}
err = json.Unmarshal(body, &someModel)

Ignoring logging situations

Ignoring logging situations in Go can lead to problems in understanding and troubleshooting your code. Logging is an essential part of debugging and maintaining software, and it allows you to keep track of what’s happening in your application and identify issues that may be causing errors or unexpected behavior.

Some common packages you can use for logging

Ignoring naming conventions

Naming conventions are essential to writing readable and maintainable code. Consistent naming conventions make it easier for developers to understand the purpose of variables, functions, and types.

Here are some general guidelines,

  • Use short, concise, meaningful names for variables, types
  • Use CamelCase ( eg : dbDataVariable , dbCreateUser )
  • Use PascalCase (eg: MyFunctionName)
  • Use Capital Letters for CONSTANTS (eg : PI)
  • Use singular nouns for variable names and plural nouns for slice or array variable names.
  • Use “err” for error variables only

Ignoring the code organization

A well organized code can be more simple, readable and maintainable. You have to separate code into packages, sub-packages and smaller functionalities. It can be easily reused across multiple projects, also it will becomes easier to scale the application as needed.

A sample code organizing structure

Also make sure to appropriately comment your code, describing what each function or piece of code does.

Ignoring the unit tests

A unit test is a function that tests a specific piece of code from a program or package. Unit testing can help us verify code behavior at the function level. Testing is crucial for ensuring code quality. Write unit tests for all functions and run them regularly to catch errors early. It allows you to ensure that your code works as expected, catch errors before they reach production, and make changes to your code without breaking existing functionality.

Ignoring go routines

Go routines are one of the most powerful features of Golang. It is a lightweight thread that can run code simultaneously. Failure to use go routines can result in inefficient code and slower performance.

Not using Go routines can be a major mistake for a Go developer,

By successfully utilizing go-routines, you can fully utilize the power of the Go language and create high-performance, scalable, and dependable applications.

Ignoring the standard library

Golang has rich set of core packages that enhance and extend the language. Failure to use the standard library may result in code duplication and make your code more difficult to manage.

Here are some standard libraries,

  • fmt : Provides functionalities for printing and formatting strings
  • sort : functions for sorting the slices and other collections
  • strings: providing functions for manipulating strings such as Replace, Join, Trim..etc
  • Time : Providing functions for times, dates, duration, time manipulations..etc

Ignoring the pointers

Pointers are the fundamental part of golang and are used extensively for memory management and data manipulation. If we ignore the use of pointers, it will raise memory utilization, reduce performance, and be unable to modify data.

When a function is called, Go creates a copy of the variable’s value and passes it to the function. This can be inefficient when working with large data structures.

Using pointers can help to avoid copying large data structures and improve performance. However, using pointers incorrectly can lead to memory leaks, dangling pointers, and other issues

var ptr *int // Always try to initialize, this will set nil , which means they don't point to any memory location

Ignoring variables scopes

If you define a variable with global scope but only use it locally within a function or a package, it can lead to issues with code maintainability and readability. It’s generally considered best practice to keep the scope of variables as narrow as possible, in order to minimize the risk of unintended side effects and to make the code easier to understand and modify.

Don’t globalize everything, keep it local!

Ignoring compatibility issues

Go has different versions, and code written for one version may not work on another version. It’s essential to consider compatibility issues and make sure that your code works on all versions of Go. Ignoring compatibility issues can also result in decreased performance, increased development time.

In conclusion, there are several common mistakes that should be avoided when coding in Golang. These include using global variables excessively, ignoring error handling, not properly utilizing goroutines, and not organizing code into packages and modules. By being aware of these potential pitfalls and taking steps to avoid them, You can optimize your coding experience and produce high-quality, efficient code.

I hope this article helps. Thank you so much for reading. :)

Feel free to share your thoughts or experiences.

Sources

--

--

PRATHEESH PC

Hey there! I'm a software developer and I'm absolutely in love with building things with technology.