Go Comments
Comments are notes in your code that are skipped when the program runs.
They are useful for explaining what the code does and making it easier to read. They also let you switch off some code while you test a different version of it.
Go has two kinds: single-line and multi-line.
Go Single-line Comments
Write two forward slashes (//) to begin a single-line comment.
From there to the end of the line, the compiler ignores everything, so none of that text gets executed.
Example
Output: Go program and captured output
package main
import ("fmt")
func main() {
// This is a comment
fmt.Println("Hello World!")
}
Example
A single-line comment doesn't need its own line. Here, one follows the code on the same line:
Output: Go program and captured output
package main
import ("fmt")
func main() {
fmt.Println("Hello World!") // This is a comment
}
Go Multi-line Comments
To write a multi-line comment, open it with /* and close it with */.
The compiler ignores all the text in between.
Note: The choice is yours. A common habit is // for short notes and /* */ for longer ones.
Example
Output: Go program and captured output
package main
import ("fmt")
func main() {
/* The code below will print Hello World
to the screen, and it is amazing */
fmt.Println("Hello World!")
}
Comment to Prevent Code Execution
Since the compiler ignores comments, you can turn a line of code into a comment to stop it from running.
The code stays in the file, ready for you to refer back to later or use while troubleshooting.
Example
Output: Go program and captured output
package main
import ("fmt")
func main() {
fmt.Println("Hello World!")
// fmt.Println("This line does not execute")
}