Comments
A comment is a note in your code for people to read. The compiler skips comments, so they do not change what the program does.
Go has two kinds of comments:
package main
import "fmt"
func main() {
// This is a one-line comment.
fmt.Println("First")
/* This comment can
use many lines. */
fmt.Println("Second")
}
Output:
First
Second
// starts a comment that goes to the end of the line. /* starts a comment that goes on until */, even over many lines. Most Go code uses // comments. You will see /* */ comments at the top of the exercises in this course, where they explain the task.
What to write in a comment
The code already shows what it does. A good comment explains why, which the code cannot show:
// 40 for the meal, plus a 5 dollar delivery fee
fmt.Println("Total:", 45)
Output:
Total: 45
Without the comment, a reader sees the number 45 and cannot know where it came from. Avoid comments that only repeat the code. // print the total above that line would tell the reader nothing new.
Commenting out a line
Put // in front of a line, and the compiler skips it. Programmers call this commenting out a line. It turns the line off for a while, without deleting it:
fmt.Println("Start")
// fmt.Println("This line is off")
fmt.Println("End") // this line runs
Output:
Start
End
The middle line is still in the file, but it did not run. To turn it back on, remove the //. This helps a lot when you look for a mistake in your program.
The last line shows that a // comment can also go at the end of a line of code. The code before the // still runs.
Watch out for unused imports
In the last lesson, you saw that Go does not allow an unused import. Commenting out a line can cause that error. Here the only line that uses fmt is commented out:
package main
import "fmt"
func main() {
// fmt.Println("Hello, Go!")
}
Output:
# command-line-arguments
./main.go:3:8: "fmt" imported and not used
Nothing in the program uses fmt anymore, so the import is unused. When this happens, comment out the import too, or bring the line back.
Now answer a question about what the compiler does with comments.