技术
Go
- 2025-12-15
- 晓宇
Hello world
1 | package main |
- Every program is made up of packages
- program starts running in package main
Functions
- Types come after the variable name
- Bellow function takes two integer and returns one integer
1 | func add(x int, y int) int { |
- Type can be crammed together if same type
1 | func add(x, y int) int { |
- Multiple values can be returned from functions
1 | func swap(x, y string) (string, string) { |
1 | $ world hello |
- Values can be returned by name. If a variable name is specified
with the return type. Those variable will be return by the function.
1 | func plus_five(x, y int) (a, b int) { |
1 | $ 15 25 |
Function can be passed to a function
A function can be closures
Variables
vardeclares a list of variables
1 | var i, j int = 10, 20 |
:=can be used for short
1 | k, isC = 25, false |
Basic Types
1 | bool |
Uninitialized variables are given default zero values. 0 for int, “” for strings
and false for boolsIf type isn’t specified explicitly type is inferenced from the context
1
2i := 10 // i is int
hello := "hello, world" // hello is stringType conversion is done with T(v)
1
2i := 10
d := float64(i)constants are declared with
constkeyword. Constants can be declared with:=.1
const PI = 3.14
Conditional statements
if/else if/else
1 | package main |
- If condition with statement. Variable scope declared in the statement
is inside if1
2
3
4
5
6
7
8
9
10
11
12
13package main
import (
"fmt"
"math"
)
func main() {
x := -20
if v := math.Abs(float64(x)); v >= 10 {
fmt.Println("Too large to process: ", v)
}
}
Switch
- No fall through cases
- Evaluates from top to bottom, stops when a case succeed
1 | package main |
- Switch without argument can be used instead of an if/else if/else chain:
1 | switch { |
Pointers
- There is no pointer arithmetical
1 | package main |
Structs
1 | package main |
- Pointers to struct can be used as
(*ptr).field. Shortcutptr.field:
1 | p := Pixel{5, 10, 0} |
- Struct initialization:
1 | a = Pixel{1, 2, 3} |
Array
1 | var arr [2]string |
Slice
- Slice are reference to an array
1 | var a [10]int |
Slices have length and capacity. Length is the number of elements and capacity
is the undelying size.makefunction can be used to create zero initialized arrays
1 | arr := make([]int, 5) // 5 length, 5 capacity |
appendfunction can be used to dynamically grow an array
1 | var arr []int // len 0, cap 0 |
- Iterate array with for range
1 | arr := []string{"hello", "world", "good", "bye"} |