Go Syntax

A Go program consists of several key components arranged in a structured way. These components include:

Tutorials dojo strip
  1. Package Declaration: This defines the package to which the file belongs.
  2. Importing Packages: External functionalities are made available by importing relevant packages.
  3. Functions: These are blocks of reusable code designed to perform specific tasks.
  4. Statements and Expressions: These provide the logic and instructions executed by the program.

Example:

Go

Explanation of the Example Code

  1. Package Declaration (Line 1): In Go, every program is part of a package. This is declared using the package keyword. The file belongs to the main package, which is mandatory for any Go program meant to be executed.
  2. Import Statement (Line 2): The import ("fmt") statement allows access to the fmt package. This package provides various functions for text formatting and printing.
  3. Whitespace (Line 3): Go ignores extra white space. A blank line, such as this one, is used to improve the readability of the code.
  4. Main Function (Line 4): The func main() {} defines the main function. This is the starting point of any Go program. The code enclosed within {} is executed when the program runs.
  5. Statement (Line 5): The fmt.Println() function from the fmt package is used to print text to the console. In this case, it displays “Hello World!” when executed.




Go Statements and Syntax Rules

  • A statement in Go, like fmt.Println("Hello World!"), represents a complete instruction for the program to execute.
  • Statements can terminate with a newline (pressing Enter) or a semicolon (;). However, in Go, semicolons are implicitly added at the end of a statement, so they are rarely seen in the source code.
  • Curly Brackets Placement: The opening { must be on the same line as the function declaration.

Example of Incorrect Syntax:

Go

This code will throw an error because the { is placed on a new line, violating Go’s syntax rules.




Compact Go Code

Although Go allows all code to be written on a single line, this approach is strongly discouraged, as it can reduce readability.

Example of Compact Code:

Go

While the above code runs correctly, it’s harder to read and should be avoided in practice.

Tutorials dojo strip