How To Write Comments in Go

Written by Gopher Guides

Comments are lines that exist in computer programs that are ignored by compilers and interpreters. Including comments in programs makes code more readable for humans as it provides some information or explanation about what each part of a program is doing.

Depending on the purpose of your program, comments can serve as notes to yourself or reminders, or they can be written with the intention of other programmers being able to understand what your code is doing.

In general, it is a good idea to write comments while you are writing or updating a program as it is easy to forget your thought process later on, and comments written later may be less useful in the long term.

Comment Syntax

Comments in Go begin with a set of forward slashes (//) and continue to the end of the line. It is idiomatic to have a white space after the set of forward slashes.

Generally, comments will look something like this:

  1. // This is a comment

Comments do not execute, so there will be no indication of a comment when running a program. Comments are in the source code for humans to read, not for computers to execute.

In a “Hello, World!” program, a comment may look like this:

hello.go

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. // Print “Hello, World!” to console
  7. fmt.Println("Hello, World!")
  8. }

In a for loop that iterates over a slice, comments may look like this:

sharks.go

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. // Define sharks variable as a slice of strings
  7. sharks := []string{"hammerhead", "great white", "dogfish", "frilled", "bullhead", "requiem"}
  8. // For loop that iterates over sharks list and prints each string item
  9. for _, shark := range sharks {
  10. fmt.Println(shark)
  11. }
  12. }

Comments should be made at the same indent as the code it is commenting. That is, a function definition with no indent would have a comment with no indent, and each indent level following would have comments that are aligned with the code it is commenting.

For example, here is how the main function is commented, with comments following each indent level of the code:

color.go

  1. package main
  2. import "fmt"
  3. const favColor string = "blue"
  4. func main() {
  5. var guess string
  6. // Create an input loop
  7. for {
  8. // Ask the user to guess my favorite color
  9. fmt.Println("Guess my favorite color:")
  10. // Try to read a line of input from the user. Print out the error 0
  11. if _, err := fmt.Scanln(&guess); err != nil {
  12. fmt.Printf("%s\n", err)
  13. return
  14. }
  15. // Did they guess the correct color?
  16. if favColor == guess {
  17. // They guessed it!
  18. fmt.Printf("%q is my favorite color!\n", favColor)
  19. return
  20. }
  21. // Wrong! Have them guess again.
  22. fmt.Printf("Sorry, %q is not my favorite color. Guess again.\n", guess)
  23. }
  24. }

Comments are made to help programmers, whether it is the original programmer or someone else using or collaborating on the project. If comments cannot be properly maintained and updated along with the code base, it is better to not include a comment rather than write a comment that contradicts or will contradict the code.

When commenting code, you should be looking to answer the why behind the code as opposed to the what or how. Unless the code is particularly tricky, looking at the code can generally answer the what or how, which is why comments are usually focused around the why.

Block Comments

Block comments can be used to explain more complicated code or code that you don’t expect the reader to be familiar with.

You can create block comments two ways in Go. The first is by using a set of double forward slashes and repeating them for every line.

  1. // First line of a block comment
  2. // Second line of a block comment

The second is to use opening tags (/*) and closing tags (*/). For documenting code, it is considered idiomatic to always use // syntax. You would only use the /* ... */ syntax for debugging, which we will cover later in this article.

  1. /*
  2. Everything here
  3. will be considered
  4. a block comment
  5. */

In this example, the block comment defines what is happening in the MustGet() function:

function.go

  1. // MustGet will retrieve a url and return the body of the page.
  2. // If Get encounters any errors, it will panic.
  3. func MustGet(url string) string {
  4. resp, err := http.Get(url)
  5. if err != nil {
  6. panic(err)
  7. }
  8. // don't forget to close the body
  9. defer resp.Body.Close()
  10. var body []byte
  11. if body, err = ioutil.ReadAll(resp.Body); err != nil {
  12. panic(err)
  13. }
  14. return string(body)
  15. }

It is common to see block comments at the beginning of exported functions in Go; these comments are also what generate your code documentation. Block comments are also used when operations are less straightforward and are therefore demanding of a thorough explanation. With the exception of documenting functions, you should try to avoid over-commenting the code and trust other programmers to understand Go, unless you are writing for a particular audience.

Inline Comments

Inline comments occur on the same line of a statement, following the code itself. Like other comments, they begin with a set of forward slashes. Again, it’s not required to have a whitespace after the forward slashes, but it is considered idiomatic to do so.

Generally, inline comments look like this:

  1. [code] // Inline comment about the code

Inline comments should be used sparingly, but can be effective for explaining tricky or non-obvious parts of code. They can also be useful if you think you may not remember a line of the code you are writing in the future, or if you are collaborating with someone who you know may not be familiar with all aspects of the code.

For example, if you don’t use a lot of math in your Go programs, you or your collaborators may not know that the following creates a complex number, so you may want to include an inline comment about that:

  1. z := x % 2 // Get the modulus of x

You can also use inline comments to explain the reason behind doing something, or to provide some extra information, as in:

  1. x := 8 // Initialize x with an arbitrary number

You should only use inline comments when necessary and when they can provide helpful guidance for the person reading the program.

Commenting Out Code for Testing

In addition to using comments as a way to document code, you can also use opening tags (/*) and closing tags (*/) to create a block comment. This allows you to comment out code that you don’t want to execute while you are testing or debugging a program you are currently creating. That is, when you experience errors after implementing new lines of code, you may want to comment a few of them out to see if you can troubleshoot the precise issue.

Using the /* and */ tags can also allow you to try alternatives while you’re determining how to set up your code. You can also use block comments to comment out code that is failing while you continue to work on other parts of your code.

multiply.go

  1. // Function to add two numbers
  2. func addTwoNumbers(x, y int) int {
  3. sum := x + y
  4. return sum
  5. }
  6. // Function to multiply two numbers
  7. func multiplyTwoNumbers(x, y int) int {
  8. product := x * y
  9. return product
  10. }
  11. func main() {
  12. /*
  13. In this example, we're commenting out the addTwoNumbers
  14. function because it is failing, therefore preventing it from executing.
  15. Only the multiplyTwoNumbers function will run
  16. a := addTwoNumbers(3, 5)
  17. fmt.Println(a)
  18. */
  19. m := multiplyTwoNumbers(5, 9)
  20. fmt.Println(m)
  21. }

Note: Commenting out code should only be done for testing purposes. Do not leave snippets of commented out code in your final program.

Commenting out code with the /* and */ tags can allow you to try out different programming methods as well as help you find the source of an error through systematically commenting out and running parts of a program.

Conclusion

Using comments within your Go programs helps to make your programs more readable for humans, including your future self. Adding appropriate comments that are relevant and useful can make it easier for others to collaborate with you on programming projects and make the value of your code more obvious.

Commenting your code properly in Go will also allow for you to use the Godoc tool. Godoc is a tool that will extract comments from your code and generate documentation for your Go program.