W3Basic Logo

Go Comments

Go supports two types of comments, Single Line Comments and Multi-line Comments.

The primary purposes of using comments in Golang are:

  • Comments are used to describe the code. Adding comments to the code makes it more human-readable and makes it easy to maintain the code.
  • We also use comments for documentation and metadata purposes.
  • Comments are the best way to block specific code from execution.

Types of Comments in Go

  • Single Line comments
  • Multi-line Comments

Single Line Comments

Single-line comments are represented using double forward slashes (//). Single-line comments are mainly used to describe the line of code; it is placed either before the line of code or after the line of code. Any code that comes after a double forward slash will be ignored and not executed.


//  Single Line Comment Example

Let us take a simple example to demonstrate a single-line comment.

package main

import "fmt"

func main() {

	// Declare constant
	const celcius float64 = 21.0

	// Formula to convert Celcius to fahrenheit
	const fahrenheit float64 = celcius*9/5 + 32

	// Print the output result
	fmt.Printf("%.2f°C is %.2f°F.\n", celcius, fahrenheit)

Multi-Line Comments

Multi-line comment, also known as block comments, starts with a forward slash followed by an asterisk /* and ends with an asterisk followed by a forward slash */

Any code that comes in between /* and */ will be ignored and not executed.

Multi-Line Comments Syntax

/* This is an example of 
multi-line comment in Go lang */

Let us take a simple example to demonstrate a multi-line comment.

package main

import "fmt"

Program to convert celcius to fahrenheit
in Go programming

func main() {
	const celcius float64 = 21.0
	const fahrenheit float64 = celcius*9/5 + 32

	fmt.Printf("%.2f°C is %.2f°F.\n", celcius, fahrenheit)

Best Practices of writing code comments

  • Do not duplicate the code while explaining the code in comment blocks.
  • Write precise and meaningful comments
  • Do not comment the code, If a peice of code is not in use it is better to delete rather then commenting it out for future use.
  • Add metadata, document style commenting which provides overiew of the code, class, methods, parameters and the return type.
  • Provide links to external references if you have reffered the code from online sources.
  • Add the comments while fixing the bugs
  • Do not overdo it

© 2023 W3Basic. All rights reserved.

Follow Us: