23 September 2017
primes := [6]int{2, 3, 5, 7, 11, 13}

var s1 []int = primes[1:4]  // 3 5 7
var s2 []int = primes[0:3]  // 2 3 5

切片是引用传递的

names := [4]string{ "one", "two", "three", "four" }

a := names[0:2]        // [one two]
b := names[1:3]        // [two three]
fmt.Println(a, b)

b[0] = "XXX"
fmt.Println(a)         // [one XXX]
fmt.Println(b)         // [XXX three]
fmt.Println(names)     // [one XXX three four]

切片文法

[3]bool{true, true, false}  // 数组
[]bool{true, true, false}   // 切片#+BEGIN_SRC go -r
func printSlice(s []int) {
        fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)   // len=6 cap=6 [2 3 5 7 11 13]

// Slice the slice to give it zero length.
s = s[:0]
printSlice(s)   // len=0 cap=6 []

// Extend its length.
s = s[:4]
printSlice(s)   // len=4 cap=6 [2 3 5 7]

// Drop its first two values.
s = s[2:]
printSlice(s)   // len=2 cap=4 [5 7]
// Create a tic-tac-toe board.
board := [][]string{
        []string{"_", "_", "_"},
        []string{"_", "_", "_"},
        []string{"_", "_", "_"},
}

// The players take turns.
board[0][0] = "X"
board[2][2] = "O"
board[1][2] = "X"
board[1][0] = "O"
board[0][2] = "X"

for i := 0; i < len(board); i++ {
        fmt.Printf("%s\n", strings.Join(board[i], " "))
}