the basics 2 Flashcards
(15 cards)
Conditionals
if x > 10 {
fmt.Println(“Large”)
} else if x > 5 {
fmt.Println(“Medium”)
} else {
fmt.Println(“Small”)
}
Conditionals shorts
if val := compute(); val < 0 {
fmt.Println(“Negative”)
}
Functions multiple
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New(“division by zero”)
}
return a / b, nil
}
Functions named
func calc(a, b int) (sum int, diff int) {
sum = a + b
diff = a - b
return // implicitly returns sum, diff
}
Exporting (Public):
Uppercase names are exported (e.g., Println, GetUser).
Importing:
go
import (
“fmt” // Standard library
“math/rand” // Subpackage
“github.com/user/pkg” // Third-party
)
Package Declaration:
package main // Executable packages use main
Type Casting Explicit
var i int = 42
var f float64 = float64(i) // int → float64
Type Inference
x := 42 // int
y := 3.14 // float64
z := “hello” // string
Arrays fixed
var arr [3]int // [0, 0, 0]
arr := [3]int{1, 2, 3} // Initialized
Key Point:
Size is part of the type ([3]int ≠ [4]int).
Slices (Dynamic Arrays)
slice := []int{1, 2, 3} // No fixed size
slice = append(slice, 4) // [1, 2, 3, 4]
sub := slice[1:3] // [2, 3] (half-open)
Underlying Array:
Slices are references to arrays.
Maps (Key-Value Pairs)
m := map[string]int{“a”: 1, “b”: 2}
m[“c”] = 3 // Insert
val, exists := m[“d”] // exists=false if missing
Key Rule:
Keys must be comparable (no slices/functions).
make() (Pre-Allocation) Slices
slice := make([]int, 3, 5) // len=3, cap=5
make() (Pre-Allocation) maps
m := make(map[string]int, 10) // Pre-allocates space
Use Case: Optimize performance by pre-sizing.
Structs
Declaration:
type User struct {
Name string
Age int
}
Usage:
u := User{“Alice”, 30}
u.Age = 31 // Mutable
Structs Embedded
type Admin struct {
User
Permissions []string
}