package main
import (
"fmt"
)
func main() {
a := [] int {1,2,3,4,5,6}
var b = a[1:5]
fmt.Println(b)
var c = a[1:]
fmt.Println(c)
var d = a[:5]
fmt.Println(d)
}
c = a[1:]與d = a[:5]表示一端到array的最遠端點。
: Slice本身就是一個array,所以可以直接宣告一個slice並使用相關函數。
package main
import (
"fmt"
"math/rand"
)
func main() {
var a [] int //長度不確定的slice
rand.Seed(9)
for i:=0; i<10; i++{
a = append(a,rand.Intn(100))
}
fmt.Println("Slice a: len =", len(a),"cap =", cap(a),"a =", a, "a[5]=", a[5])
var b = make([]int, 3, 5) // [] int{0,0,0,0,0} >> length=5, capacity=5
fmt.Println("Slice b: len =", len(b),"cap =", cap(b),"b =", b)
b = append(b, 10,20,30)
fmt.Println("Slice b: len =", len(b),"cap =", cap(b),"b =", b)
var c = make([]int, len(b), cap(b))
copy(c,b)
fmt.Println("Slice c: len =", len(c),"cap =", cap(c),"c =", c)
}
package main
import (
"fmt"
)
func main() {
var mapOne = map[string]int{"one":1, "two":2, "three":3, "four":4, "five":5}
fmt.Println(mapOne["one"] + mapOne["two"])
delete(mapOne, "five")
fmt.Println(mapOne)
value, ok := mapOne["six"]
if ok{
fmt.Println(value, "exists.")
}else{
fmt.Println("no value contained.", value)
}
}
value, ok := mapOne["six"]表示如果mapOne["six"]存在,value = mapOne["six"]的值,ok為true,否則ok為false,value為0。
Range
range是用來在for loop中iterate over一個array, slice, channel or map的關鍵字。
: 建立一個iterable物件並使用for loop搭配range。
package main
import (
"fmt"
)
func main() {
var a [] int //長度不確定的slice
rand.Seed(9)
for i:=0; i<5; i++{
a = append(a,rand.Intn(100))
}
var sum = 0
for i:=range a{
sum = sum + a[i]
}
fmt.Printf("sum = %d\n", sum)
sum = 0
for i:=0; i
i:=range a中i為a的index。
: range用在map。
package main
import (
"fmt"
)
func main() {
var mapOne = map[string]int{"one":1, "two":2, "three":3, "four":4, "five":5}
for k:=range mapOne{
fmt.Println(k, ">>", mapOne[k])
}
fmt.Println(mapOne)
for k, v := range mapOne{
fmt.Println(k, ">>", v)
}
}