go语言基础之切片的创建和截取

1、切片的创建

示例:

package main //必须有个main包

import "fmt"

func main() {
	//切片和数组的区别
	//数组[]里面的长度时固定的一个常量, 数组不能修改长度, len和cap永远都是5
	a := [5]int{}
	fmt.Printf("len = %d, cap = %d\n", len(a), cap(a))

	//切片, []里面为空,或者为...,切片的长度或容量可以不固定
	s := []int{}
	fmt.Printf("1: len = %d, cap = %d\n", len(s), cap(s))

	s = append(s, 11) //给切片末尾追加一个成员
	fmt.Printf("append: len = %d, cap = %d\n", len(s), cap(s))

}

执行结果:

len = 5, cap = 5
1: len = 0, cap = 0
append: len = 1, cap = 1  

  

2、切片的截取

切片语法:

操作

含义

s[n]

切片s中索引位置为n的项

s[:]

从切片s的索引位置0到len(s)-1处所获得的切片

s[low:]

从切片s的索引位置low到len(s)-1处所获得的切片

s[:high]

从切片s的索引位置0到high处所获得的切片,len=high

s[low:high]

从切片s的索引位置low到high处所获得的切片,len=high-low

s[low:high:max]

从切片s的索引位置low到high处所获得的切片,len=high-low,cap=max-low

len(s)

切片s的长度,总是<=cap(s)

cap(s)

切片s的容量,总是>=len(s)

 

示例:

package main //必须有个main包

import "fmt"

func main() {
	array := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	//[low:high:max] 取下标从low开始的元素, len=high-low, cap=max-low
	s1 := array[:] //[0:len(array):len(array)] 不指定容量和长度一样
	fmt.Println("s1 = ", s1)
	fmt.Printf("len = %d, cap = %d\n", len(s1), cap(s1))

	//操作某个元素,和数组操作方式一样
	data := array[1]
	fmt.Println("data = ", data)

	s2 := array[3:6:7] //a[3], a[4], a[5]   len = 6-3=3    cap = 7-3=4
	fmt.Println("s2 = ", s2)
	fmt.Printf("len = %d, cap = %d\n", len(s2), cap(s2))

	s3 := array[:6] //从0开始,去6个元素,容量也是6, 常用
	fmt.Println("s3 = ", s3)
	fmt.Printf("len = %d, cap = %d\n", len(s3), cap(s3))

	s4 := array[3:] //从下标为3开始,到结尾
	fmt.Println("s4 = ", s4)  //[3 4 5 6 7 8 9]
	fmt.Printf("len = %d, cap = %d\n", len(s4), cap(s4))
}

执行结果:

s1 = [0 1 2 3 4 5 6 7 8 9]

len = 10, cap = 10

data = 1

s2 = [3 4 5]

len = 3, cap = 4

s3 = [0 1 2 3 4 5]

len = 6, cap = 10

s4 = [3 4 5 6 7 8 9]

len = 7, cap = 7

  

 

posted @ 2019-01-08 15:57  努力哥  阅读(2681)  评论(0编辑  收藏  举报