go基础_切片

切片创建方式

1.通过数组创建

2.通过内置函数make创建

切片允许的操作

1.追加元素

2.通过内置函数make创建

package main

import "fmt"

func main() {
	//创建切片,从数组创建
	array := [5]int{1, 2, 3, 4, 5}
	s := array[0:4]
	fmt.Println(s)

	//创建切片,长度5,容量5
	a := make([]int, 5)
	fmt.Println("array is:", a, "len is:", len(a), "cap is:", cap(a))

	//创建切片,长度5,容量12
	b := make([]int, 5, 12)
	fmt.Println("array is:", b, "len is:", len(b), "cap is:", cap(b))

	//切片追加1个元素
	c := append(b, 3)
	fmt.Println(c)
}

运行结果

/Users/liurong07/go/bin/go run hello.go [/Users/liurong07/Documents/code/QA/go_test]
[1 2 3 4]
array is: [0 0 0 0 0] len is: 5 cap is: 5
array is: [0 0 0 0 0] len is: 5 cap is: 12
[0 0 0 0 0 3]
成功: 进程退出代码 0.

  

猜你喜欢

转载自www.cnblogs.com/liurong07/p/10576609.html