Lesson 3 of 60 · Go
Basic Syntax: Packages, Functions, and Variables
Duration: 20 minutes
Basic Syntax: Packages, Functions, and Variables
This lesson explains how Go programs are structured and how to declare values, variables, and functions.
Packages
Every Go source file starts with a package declaration. A package groups related Go files together.
package main
The main package is used for executables. Other packages are reusable libraries.
Imports
Use import to bring in code from the standard library or external modules.
import "fmt"
Variables
Declare variables with explicit types or let Go infer the type from the value.
var a int // zero-value 0
var b string // zero-value ""
var c = true // type inferred
Go gives each uninitialized variable a zero value: 0, "", false, or nil for pointers, slices, maps, and interfaces.
Short variable declaration
Inside functions, use := for shorter declarations.
x := 42
msg := "Go is fun"
Functions
Functions are declared with func, and parameters and return types are explicit.
func add(a, b int) int {
return a + b
}
func main() {
fmt.Println(add(3, 4))
}
Functions can also return multiple values, which is common in Go.
func swap(a, b string) (string, string) {
return b, a
}