切片含义
切片的本质就是对底层数组的封装,它包含了三个信息:底层数组的指针、切片的长度(len)和切片的容量(cap)。
切片练习题
/*
@Time : 2020-03-12 14:35
@Author : ianthony
@File : main
@Software: GoLand
*/
package main
import "fmt"
func main() {
// 定义一个切片
var s1 []int
var s2 []string
// 切片初始哈
s1 = []int{1, 2, 3}
s2 = []string{"海淀", "张江", "朝阳"}
fmt.Printf("len:%d,cap:%d\n", len(s1), cap(s1))
fmt.Printf("len:%d,cap:%d\n", len(s2), cap(s2))
// 将数组切割
a1 := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 445, 631}
b1 := a1[0:4]
fmt.Println(b1)
//切片再切片
a := [...]string{"北京", "上海", "广州", "深圳", "成都", "重庆"}
fmt.Printf("a:%v type:%T len:%d cap:%d\n", a, a, len(a), cap(a))
b := a[1:3]
fmt.Printf("b:%v type:%T len:%d cap:%d\n", b, b, len(b), cap(b))
c := b[1:5]
fmt.Printf("c:%v type:%T len:%d cap:%d\n", c, c, len(c), cap(c))
// 生成一个切片
a2 := make([]int, 2, 10)
fmt.Println(a2)
fmt.Println(len(a2))
fmt.Println(cap(a2))
// 切片赋值
a2[1] = 2
fmt.Println(a2)
var s []int
var t []string
s = append(s, 1, 2, 3, 4)
t = append(t, "一", "二", "三")
fmt.Println(s)
fmt.Println(t)
}
|
请发表评论