Comments in Go are non-executable lines of text that help explain the code, improve its readability, or temporarily disable portions of it for testing and debugging. Go offers two types of comments: single-line and multi-line.
Go Single-line Comments
Single-line comments begin with //
. Any text following //
on the same line is ignored by the compiler.
Example:
This program demonstrates the use of single-line comments:
// This program displays a message about Yamaha
package main
import ("fmt")
func main() {
// Printing a Yamaha-themed message
fmt.Println("Experience the thrill with Yamaha!")
}
Single-line comments can also be placed at the end of a code line:
package main
import ("fmt")
func main() {
fmt.Println("Honda: The Power of Dreams!") // Displays Honda's tagline
}
Go Multi-line Comments
Multi-line comments are enclosed within /*
and */
. They are perfect for providing detailed descriptions spanning multiple lines.
Example:
This program includes a multi-line comment to describe its purpose:
/* This program introduces Suzuki's spirit
and prints a message highlighting the brand. */
package main
import ("fmt")
func main() {
fmt.Println("Suzuki: Way of Life!")
}
Commenting to Disable Code Execution
Comments can also be used to prevent certain lines from executing, which is useful for testing alternative logic or debugging.
Example:
In this program, one line of code is disabled:
// This program demonstrates how to disable code
package main
import ("fmt")
func main() {
fmt.Println("This line is active and will execute.")
// fmt.Println("This line is commented out and won't execute.")
}
Tips for Using Comments
- Use single-line comments (
//
) for brief annotations or explanations. - Use multi-line comments (
/* ... */
) when more extensive notes or documentation are required. - Temporarily disable code using comments to simplify testing and debugging.