Go Basic Syntax Tutorial
Go's syntax combines C-like structure with modern simplicity. This tutorial explains Go's fundamental concepts through clear explanations and minimal essential examples.
1. Program Structure
Every Go program follows a specific structure that the compiler expects:
package main
import "fmt"
func main() {
fmt.Println("Basic structure")
}
Package Declaration: The package main declaration identifies this as an executable program (as opposed to a library). Only packages named "main" can be executed.
Imports: The import statement brings in other packages. The fmt package (format) is part of Go's standard library and handles input/output operations.
Main Function: func main() serves as the program's entry point. When you run a Go program, execution begins here.
Structure Quiz
What makes a Go file executable?
2. Variables and Constants
Go is statically typed but supports type inference to reduce verbosity.
var explicit int = 10
implicit := "type inferred"
const pi = 3.14159
Variable Declaration: The var keyword declares variables with explicit types. The shorthand := syntax both declares and initializes variables with type inference.
Constants: Declared with const, these are immutable values that must be determinable at compile time. They can be character, string, boolean, or numeric values.
Naming Rules: Must begin with letter/underscore, are case-sensitive, and uppercase names are exported (visible outside package).
Variables Quiz
What's the difference between var and := ?
3. Control Flow
Go provides standard control structures with minimal syntax.
if x > 10 {
// if block
} else {
// else block
}
for i := 0; i < 5; i++ {
// traditional for
}
switch day {
case "Mon":
// case 1
default:
// default case
}
If Statements: Conditions don't need parentheses but braces are required. Can include optional else if and else clauses.
For Loops: Go's only looping construct that serves as both traditional for and while loop. The infinite loop is written as for {}.
Switch Statements: More flexible than C-style switches. Cases don't fall through by default (no need for break). Can switch on any type.
Control Quiz
How do you write an infinite loop in Go?
4. Functions
Functions are first-class citizens in Go with several unique features.
func greet(name string) string {
return "Hello " + name
}
func multiReturn() (int, error) {
return 42, nil
}
func variadic(nums ...int) int {
// nums is a slice
}
Basic Functions: Declared with func keyword. Parameters come before return type. Can return multiple values, commonly used for returning a result plus an error.
Variadic Functions: Accept variable number of arguments via ... syntax. The parameters become a slice inside the function.
Named Returns: Return values can be named and treated as variables. A "naked" return statement will return the current values of those variables.
Functions Quiz
How does Go handle errors?
5. Collections
Go provides three main collection types with distinct characteristics.
array := [3]int{1, 2, 3} // Fixed size
slice := []int{1, 2, 3} // Dynamic size
mapping := map[string]int{"a": 1}
Arrays: Fixed-size sequences that hold elements of the same type. The size is part of the type (e.g., [3]int is a different type than [4]int).
Slices: Dynamic views into arrays. More commonly used than arrays directly. Can grow/shrink using append. Have both length and capacity.
Maps: Key-value stores similar to dictionaries. Keys must be comparable types. Safe to query non-existent keys (returns zero value).
Collections Quiz
What happens when you query a non-existent map key?
6. Structs and Methods
Go uses structs instead of classes for creating custom types.
type Person struct {
Name string
Age int
}
func (p Person) Greet() {
fmt.Println(p.Name)
}
func (p *Person) Birthday() {
p.Age++
}
Structs: Collections of named fields that define a new type. No inheritance but supports composition through embedding. Fields are accessed with dot notation.
Methods: Functions with receiver arguments that operate on a type. Value receivers work on copies while pointer receivers modify the original.
Constructors: While Go doesn't have constructors, it's common to use factory functions (like NewPerson()) for initialization logic.
Structs Quiz
When should you use a pointer receiver?
7. Interfaces
Go's interfaces provide polymorphism through implicit implementation.
type Speaker interface {
Speak() string
}
type Dog struct{}
func (d Dog) Speak() string {
return "Woof!"
}
Interface Definition: Specifies a set of method signatures. Types implicitly satisfy interfaces by implementing all required methods - no explicit declaration needed.
Empty Interface: The interface{} type has zero methods and can hold values of any type, often used for generic programming before generics were added.
Type Assertions: Used to extract the concrete value from an interface. Can test whether a value satisfies an interface using the comma-ok idiom.
Interfaces Quiz
How does a type implement an interface?