ProgramGuru

Comments

Start with Go Comments

Comments are notes for people reading the code. The Go compiler ignores their contents when executing instructions.

What you’ll learn

  • Write line and block comments.
  • Separate explanatory text from executable statements.
  • Recognize documentation-comment conventions.

Understand the idea

Write a single-line comment with //. Use /* ... */ for a block comment. A comment should explain intent or a non-obvious decision, rather than restating code that is already clear.

Go documentation comments conventionally begin with the name of the item they describe, for example // Add returns .... A comment can appear above code or after a statement, but it does not change a variable’s value.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	// Start with the available seats.
	seats := 12
	/* Two more seats become available. */
	seats += 2
	fmt.Println("Seats:", seats)
}

Output

Seats: 14

Trace what the program does

The first comment tells the reader what the initial value represents. The block comment adds context about the change. Only the assignment and addition affect the final count.

Avoid common mistakes

  • Do not store important explanations only in comments while leaving misleading variable names in place.
  • Block comments must be closed with */; forgetting the terminator causes a syntax error.

Try it yourself

Remove the comments and run again. Does the output change? Then add a comment explaining why the count increases.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Which line is ignored as an instruction by the compiler?
Choose one answer. You can try again.

Answer and explanation

// Start with available seats.

Correct. The first comment tells the reader what the initial value represents.

What you should remember

You have practiced Go Comments in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Variables →