Features
Variables and Constants
var flag bool
var count int64
var ratio float32
var student1 string = "John" //type is string
var student2 = "Jane" //type is inferred
x := 2
var a, b, c, d int = 1, 3, 5, 7
e, f := 100, "World!"
var (
g int
h int = 1
i string = "hello"
)
const (
PI = 3.14
MAX_COUNT = 10000
)
Types
Array
// Initialize only specific elements
arr1 := [5]int{1:10,2:40}
// Find the length of an array
arrLen := len(arr1)
Slice
Unlike arrays, the length of a slice can grow and shrink
mySlice := []int{}
// Create a slice from an array
myArr := [6]int{10, 11, 12, 13, 14,15}
mySlice := myArr[2:4]
// Create a slice with the make()
// slice_name := make([]type, length, capacity)
mySlice := make([]int, 5)
// Append elements to a slice
mySlice = append(mySlice, 20, 21)
// Append one slice to another slice
mySlice1 := []int{1,2,3}
mySlice2 := []int{4,5,6}
mySlice3 := append(mySlice1, mySlice2)
// Create copy with only needed numbers
numbers := []int{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
neededNumbers := numbers[:len(numbers)-10]
numbersCopy := make([]int, len(neededNumbers))
copy(numbersCopy, neededNumbers)
Map
myMap := map[string]int{"Oslo": 1, "Bergen": 2, "Trondheim": 3, "Stavanger": 4}
// Create maps using make()
myMap := make(map[string]int)
// Remove element from map
delete(myMap, "year")
//Check for specific elements in a map
_, ok := myMap["model"]
// Use range to iterate over maps
for k, v := range myMap {
fmt.Printf("%v : %v\n", k, v)
}
Struct
type Person struct {
name string
age int
job string
salary int
}
Special Keywords
Range
fruits := [3]string{"apple", "orange", "banana"}
for idx, val := range fruits {
fmt.Printf("%v\t%v\n", idx, val)
}
Defer
Go
Function
func myFunction(x int, y int) int {
return x + y
}
// Named return values
func myFunction(x int, y int) (result int) {
result = x + y
return
}
// Multiple return values
func myFunction(x int, y string) (result int, txt1 string) {
result = x + x
txt1 = y + " World!"
return
}
a, b := myFunction(5, "Hello")
Generics
func Map[T1, T2 any](arr []T1, fn func(T1) T2) []T2 {
newArr := make([]T2, len(arr))
for i := 0; i < len(arr); i++ {
newArr[i] = fn(arr[i])
}
return newArr
}
func main() {
names := []string{"Evan", "OMG", "Andy"}
lens := Map(names, func(s string) int { return len(s) })
fmt.Println(lens) // [4 3 4]
}
Testing
實用 VS Code Plugin
go test -v -cover ./...
go test -bench=^BenchmarkSum$