Go Syntax Explained

Go Syntax Explained

Kishore V


Go Syntax Explained

Understanding Go syntax is the first step toward writing clean and efficient Go programs. Go is designed with simplicity and readability in mind, making it easier to learn and maintain compared to many other programming languages.

Basic Structure of a Go Program

A typical Go source file consists of the following components:

  • Package declaration
  • Import statements
  • Functions
  • Statements and expressions

Let’s break this down with a simple example.

Example: Basic Go Program

Learning Go syntax step by step

Explanation of Each Component

1. Package Declaration

package main
  • Every Go file must belong to a package
  • The main package is special—it defines an executable program
  • Programs start execution from the main() function inside this package

2. Import Statement

import "fmt"
  • The import keyword is used to include standard or external packages
  • fmt (format package) is commonly used for input and output operations

3. Function Definition

func main() { ... }
  • func defines a function
  • main() is the entry point of the program
  • Code inside {} is executed when the program runs

4. Statements and Expressions

fmt.Println("Learning Go syntax step by step")
  • This is a statement that prints output to the console
  • Functions from imported packages are accessed using dot notation (fmt.Println)

Go Statements and Semicolons

In Go, statements are typically written on separate lines:

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

Important Notes:

  • Go automatically inserts semicolons (;) at the end of each line
  • You usually do not need to write semicolons manually
  • Writing multiple statements on one line is allowed but discouraged

Curly Braces Rule in Go

Go enforces a strict formatting rule:

Incorrect (will cause a compilation error):

func main() { fmt.Println("Invalid formatting") }

Correct:

func main() { fmt.Println("Proper formatting") }

The opening { must be on the same line as the function declaration

Example: Multiple Statements in Go

Here’s a slightly more practical example:

Sum: 8

Writing Compact Code (Not Recommended)

Go allows writing compact code using semicolons, but it reduces readability.

Compact but hard to read

Why Avoid This?

  • Harder to read and maintain
  • Not aligned with Go’s clean coding philosophy
  • Goes against standard formatting tools like gofmt


Our website uses cookies to enhance your experience. Learn More
Accept !