Go Comments

Go Tutorial

 Go Comments (Golang)

In Go Comments are used to explain code, improve readability, and help in documentation.
Go supports two types of comments.


1️⃣ Single-line

Used for short explanations.

// This is a single-line comment
fmt.Println("Hello Go")

👉 Everything after // on the same line is ignored by the compiler.


2️⃣ Multi-line (Block)

Used for longer explanations or documentation blocks.

/*
This is a multi-line comment
It can span multiple lines
*/

fmt.Println("Go Comments")

3️⃣ Inline

Used on the same line as code.

x := 10 // variable declaration

4️⃣ Commenting Out Code (Debugging)

// fmt.Println("This line will not execute")

Or:

/*
fmt.Println("Line 1")
fmt.Println("Line 2")
*/


5️⃣ Documentation Comments (Very Important in Go)

Go uses special comments to generate documentation using godoc.

Function

// add returns the sum of two integers.
func add(a int, b int) int {
return a + b
}

Package

// Package mathutils provides mathematical utility functions.
package mathutils

⚠️ Rule:
Documentation comments must start with the name of the item (function, package, struct).


6️⃣ Best Practices

✔ Keep It simple and clear
✔ Explain why, not obvious what
✔ Avoid unnecessary use It.


Summary

Comment Type Syntax
Single-line //
Multi-line /* */
Documentation // Name ...

You may also like...