切片是Go語言中的關(guān)鍵數(shù)據(jù)類型,為序列提供了比數(shù)組更強大的接口。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請參考:http://www.yiibai.com/go/go_environment.html
與數(shù)組不同,切片(slice)只是由它們包含的元素(而不是元素的數(shù)量)鍵入。要創(chuàng)建非零長度的空切片,請使用內(nèi)置make()函數(shù)。這里創(chuàng)建一個長度為3的字符串(初始為零值)。
我們可以像數(shù)組一樣設(shè)置和獲取字符串的子串值。len()函數(shù)返回切片的長度。
除了這些基本操作之外,切片還支持更多,使它們比數(shù)組更豐富。一個是內(nèi)置 append()函數(shù),它返回包含一個或多個新值的切片。注意,需要接收append()函數(shù)的返回值,因為可能得到一個新的slice值。
也可以復制切片。這里創(chuàng)建一個與切片s相同長度的空切片c,并從切片s復制到c中。切片支持具有語法為slice[low:high]的切片運算符。 例如,這獲得元素s[2],s[3]和s[4]的切片。
這切片到(但不包括)s[5]。這切片從(包括)s[2]。可以在一行中聲明并初始化slice的變量。
切片可以組成多維數(shù)據(jù)結(jié)構(gòu)。內(nèi)切片的長度可以變化,與多維數(shù)組不同。
看看這個博客文章了解Go團隊的設(shè)計和切片在Go的實現(xiàn)的更多細節(jié)。
現(xiàn)在已經(jīng)看到了數(shù)組和切片,看看Go編程的其他關(guān)鍵內(nèi)置數(shù)據(jù)結(jié)構(gòu):maps。
slices.go的完整代碼如下所示 -
package main
import "fmt"
func main() {
// Unlike arrays, slices are typed only by the
// elements they contain (not the number of elements).
// To create an empty slice with non-zero length, use
// the builtin `make`. Here we make a slice of
// `string`s of length `3` (initially zero-valued).
s := make([]string, 3)
fmt.Println("emp:", s)
// We can set and get just like with arrays.
s[0] = "a"
s[1] = "b"
s[2] = "c"
fmt.Println("set:", s)
fmt.Println("get:", s[2])
// `len` returns the length of the slice as expected.
fmt.Println("len:", len(s))
// In addition to these basic operations, slices
// support several more that make them richer than
// arrays. One is the builtin `append`, which
// returns a slice containing one or more new values.
// Note that we need to accept a return value from
// append as we may get a new slice value.
s = append(s, "d")
s = append(s, "e", "f")
fmt.Println("apd:", s)
// Slices can also be `copy`'d. Here we create an
// empty slice `c` of the same length as `s` and copy
// into `c` from `s`.
c := make([]string, len(s))
copy(c, s)
fmt.Println("cpy:", c)
// Slices support a "slice" operator with the syntax
// `slice[low:high]`. For example, this gets a slice
// of the elements `s[2]`, `s[3]`, and `s[4]`.
l := s[2:5]
fmt.Println("sl1:", l)
// This slices up to (but excluding) `s[5]`.
l = s[:5]
fmt.Println("sl2:", l)
// And this slices up from (and including) `s[2]`.
l = s[2:]
fmt.Println("sl3:", l)
// We can declare and initialize a variable for slice
// in a single line as well.
t := []string{"g", "h", "i"}
fmt.Println("dcl:", t)
// Slices can be composed into multi-dimensional data
// structures. The length of the inner slices can
// vary, unlike with multi-dimensional arrays.
twoD := make([][]int, 3)
for i := 0; i < 3; i++ {
innerLen := i + 1
twoD[i] = make([]int, innerLen)
for j := 0; j < innerLen; j++ {
twoD[i][j] = i + j
}
}
fmt.Println("2d: ", twoD)
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run slices.go
emp: [ ]
set: [a b c]
get: c
len: 3
apd: [a b c d e f]
cpy: [a b c d e f]
sl1: [c d e]
sl2: [a b c d e]
sl3: [c d e f]
dcl: [g h i]
2d: [[0] [1 2] [2 3 4]]