Go Basics
Learn the fundamental concepts of Go programming language
Go Basics
Go (often referred to as Golang) is a statically typed, compiled programming language designed at Google. It's known for its simplicity, efficiency, and excellent support for concurrent programming.
Why Go?
Go was created to address common criticisms of other languages while maintaining their positive characteristics:
- Simple and readable - Clean syntax that's easy to learn
- Fast compilation - Compiles to machine code quickly
- Garbage collected - Automatic memory management
- Built-in concurrency - Goroutines and channels for concurrent programming
- Standard library - Rich set of built-in packages
Installing Go
To get started with Go, you'll need to install it on your system:
macOS
brew install go
Linux
wget https://go.dev/dl/go1.21.0.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.21.0.linux-amd64.tar.gz
export PATH=$PATH:/usr/local/go/bin
Windows
Download the installer from go.dev and run it.
Your First Go Program
Create a file called hello.go:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Run it with:
go run hello.go
Basic Syntax
Variables
Go has several ways to declare variables:
// Explicit type declaration
var name string = "John"
var age int = 30
// Type inference
var city = "New York" // Go infers string type
// Short declaration (only inside functions)
country := "USA" // := declares and initializes
Data Types
Go has several built-in data types:
// Basic types
var b bool = true
var s string = "hello"
var i int = 42
var f float64 = 3.14
// Composite types
var arr [5]int // Array
var slice []int // Slice
var m map[string]int // Map
var ch chan int // Channel
Functions
Functions are first-class citizens in Go:
// Basic function
func add(x int, y int) int {
return x + y
}
// Multiple return values
func swap(x, y string) (string, string) {
return y, x
}
// Named return values
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return // "naked" return
}
Control Structures
If Statements
if x > 0 {
fmt.Println("x is positive")
} else if x < 0 {
fmt.Println("x is negative")
} else {
fmt.Println("x is zero")
}
// If with initialization
if v := math.Pow(x, n); v < limit {
return v
}
Loops
Go has only one looping construct: for
// Traditional for loop
for i := 0; i < 10; i++ {
fmt.Println(i)
}
// While-style loop
for x < 100 {
x += x
}
// Infinite loop
for {
// Break or return to exit
}
// Range loop
numbers := []int{1, 2, 3, 4, 5}
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
Next Steps
Now that you understand the basics of Go, you're ready to explore more advanced topics:
- Structs and methods
- Interfaces
- Error handling
- Goroutines and concurrency
- Package management
- Testing
Go's simplicity makes it easy to learn, but it's powerful enough to build large-scale applications. Keep practicing and exploring the standard library!
Hello World
package main
import "fmt"
func main() {
fmt.Println("Hello, Go!")
}
Variable Declarations
// Package level
var global = "I'm global"
func main() {
// Different ways to declare
var a int = 10
var b = 20
c := 30
// Multiple variables
var x, y int = 1, 2
var (
name string = "Go"
version float64 = 1.21
)
}
Common Types
// Basic types
bool
string
int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64
byte // alias for uint8
rune // alias for int32
float32 float64
complex64 complex128
// Zero values
var i int // 0
var f float64 // 0.0
var b bool // false
var s string // ""
Type Conversions
var i int = 42
var f float64 = float64(i)
var u uint = uint(f)
// Or more simply
i := 42
f := float64(i)
u := uint(f)
Constants
const Pi = 3.14
const (
StatusOK = 200
StatusNotFound = 404
)
// Iota
const (
Sunday = iota // 0
Monday // 1
Tuesday // 2
// ...
)
Arrays and Slices
// Arrays (fixed size)
var a [5]int
a[0] = 10
a[1] = 20
// Slices (dynamic)
var s []int
s = append(s, 1)
s = append(s, 2, 3, 4)
// Make slice
slice := make([]int, 5) // len=5
slice2 := make([]int, 0, 5) // len=0, cap=5
// Slice literal
nums := []int{1, 2, 3, 4, 5}
Maps
// Declare
var m map[string]int
m = make(map[string]int)
m["answer"] = 42
// Map literal
scores := map[string]int{
"Alice": 95,
"Bob": 87,
}
// Check existence
value, exists := scores["Charlie"]
if exists {
fmt.Println(value)
}
// Delete
delete(scores, "Bob")
Function Examples
// Simple function
func greet(name string) string {
return "Hello, " + name
}
// Multiple returns
func divmod(a, b int) (int, int) {
return a / b, a % b
}
// Variadic function
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
// Function as value
var fn func(int) int
fn = func(x int) int {
return x * x
}
Struct Example
type Person struct {
Name string
Age int
}
// Create instances
p1 := Person{"Alice", 30}
p2 := Person{Name: "Bob", Age: 25}
p3 := new(Person)
p3.Name = "Charlie"
p3.Age = 35
Quick Commands
# Run a program
go run main.go
# Build executable
go build main.go
# Format code
go fmt main.go
# Get dependencies
go get github.com/pkg/errors
# Run tests
go test ./...
# Install a tool
go install github.com/tool/cmd@latest