Go Syntax

Basic Structure of a Go Program

- Every Go program has a clear and consistent structure. Here's a breakdown of the core components that make up a basic Go file:

package main

- This defines the **package name**. In Go, programs are organized into packages. The main package is special—it's the entry point for an executable program. If your file does not declare package main, the Go compiler assumes you're writing a reusable library, not something that can run directly.

import "fmt"

- Go requires you to explicitly import any packages your program uses. The "fmt" package is part of Go's standard library and is used here to handle formatted output (like printing to the console).

func main()

- This is the **entry point** of the program. When you run a Go program, execution starts at the main function. It must be named exactly main and must reside in the main package.

main()

- Inside the main() function, you write the logic you want to execute when the program runs. In this example, it simply prints a message using fmt.Println().

Structure Example:

package main

import "fmt"

func main() {
    fmt.Println("Hello, Go!")
}

Note: Omitting any of these pieces will result in a compile-time error if you're trying to run the program as an executable.

Semicolons and Braces

Go automatically inserts semicolons where appropriate, so you usually don’t need to type them. However, braces must follow the line immediately:

if x > 0 {
    fmt.Println("Positive")
}

Incorrect:

if x > 0
{ // ❌ this will cause a syntax error
    fmt.Println("Invalid brace placement")
}

Indentation and Line Endings

Go enforces formatting via gofmt. Use tabs or spaces consistently. Statements end by newline — no need for semicolons.

Format Verbs in Go

Go uses fmt.Printf with format verbs (placeholders starting with %) to print values in a formatted way:

fmt.Printf("%s is %d years old", "Alice", 30)    // Alice is 30 years old

Common Format Verbs:

VerbDescriptionExample Output
%sstring"hello"
%ddecimal (base 10 int)42
%ffloat (decimal)3.14
%tbooleantrue
%vdefault format (any type)varies

Use fmt.Printf when you want precise control over output formatting.

Comments

Go supports:

  • // for single-line comments
  • /* */ for multi-line comments
// This is a comment

/*
This is a
multi-line comment
*/

Entry Point

The main function in the main package is the program's starting point.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic