Learn Golang in 21 Days - Day 10
知识点
- 切片Slice
- Slice是对数组的抽象
- Go数组的长度不可改变,Go内置Slice动态数组
定义切片
var identifier []type
var slice1 []type = make([]type, len)
//可以简写
slice1 := make([]type, len)
切片初始化
s :=[] int {1,2,3,4,5}
a := s[2:3]
//直到最后一个元素
b := s[:4]
s := make([]int, len, cap)
len()和cap()函数
- 切片是可以索引的,并且可以由len()方法获取长度
- 切片提供了计算容量的方法cap()可以测量切片最长可以达到多少
package main
import "fmt"
func main() {
var numbers = make([]int, 3,5)
printSlice(numbers)
}
func printSlice(x []int) {
fmt.Printf("len=%d, cap=%d, slice=%v\n", len(x), cap(x), x)
}
nil slice
package main
import "fmt"
func main() {
var numbers []int
printSlice(numbers)
if(numbers == nil) {
fmt.Printf("slice is nil")
}else{
fmt.Printf("slice is not nil")
}
}
func printSlice(x []int) {
fmt.Printf("len=%d,cap=%d,slice=%v\n",len(x),cap(x),x)
}
Slice截取
- 通过设置下限和上限来设置切片[low-bound:upper-bound],实例如下:
package main
import "fmt"
func main() {
//创建切片
numbers := []int {0,1,2,3,4,5,6,7,8,9}
printSlice(numbers)
//打印原始切片
fmt.Println("numbers == ", numbers)
//打印子切片从索引1到索引4
fmt.Println("numbers[1:4] == ", numbers[1:4])
//默认下限0
fmt.Println("numbers[:3] == ", numbers[:3])
//默认上限为len(s)
fmt.Println("numbers[4:] ==", numbers[4:])
numbers1 := make([]int, 0,5)
printSlice(numbers1)
// 换一种方式初始化slice
numbers2 := numbers1[2:8]
printSlice(numbers2)
// 换一种方式初始化slice
numbers3 := numbers1[:8]
printSlice(numbers3)
}
func printSlice(x []int) {
fmt.Printf("len=%d,cap=%d,slice=%v\n",len(x),cap(x),x)
}
append() 和 copy()
- 如果想增加切片的容量,我们必须创建一个新的更大的切片并把原分片的内容都拷贝过来
- 下面的代码描述了从拷贝切片的copy方法和向切片追加新元素的append方法
package main
import "fmt"
func main() {
var numbers []int
printSlice(numbers)
// 允许追加空切片
numbers = append(numbers, 0)
printSlice(numbers)
// 向切片添加一个元素
numbers = append(numbers,1)
printSlice(numbers)
// 同时添加多个元素
numbers = append(numbers, 2,3,4)
printSlice(numbers)
// 扩容slice
numbers1 := make([]int, len(numbers), (cap(numbers)*2))
printSlice(numbers1)
// copy
copy(numbers1, numbers)
fmt.Println("---------------")
printSlice(numbers1)
}
func printSlice(x []int) {
fmt.Printf("len=%d,cap=%d,slice=%v\n",len(x),cap(x),x)
}
网友评论