go 切片

一、切片是什么:

切片是对数组一个连续片段的引用,所以切片是一个引用类型。

特点:切片是一个长度可变的数组

一个由数字 1、2、3 组成的切片可以这么生成:s := [3]int{1,2,3}[:] 甚至更简单的 s := []int{1,2,3}

二、小例子:

len(s) <= cap(s)
package main

import "fmt"

func main() {
	var arr1 [6]int
	var slice1 []int = arr1[2:5] // item at index 5 not included!

	// load the array with integers: 0,1,2,3,4,5
	for i := 0; i < len(arr1); i++ {
		arr1[i] = i
		fmt.Printf("%d is %d
",i,arr1[i])
	}

	// print the slice
	for i := 0; i < len(slice1); i++ {
		fmt.Printf("Slice at %d is %d
", i, slice1[i])
	}

	fmt.Printf("The length of arr1 is %d
", len(arr1))
	fmt.Printf("The length of slice1 is %d
", len(slice1))
	fmt.Printf("The capacity of slice1 is %d
", cap(slice1))
}

  输出:

0 is 0
1 is 1
2 is 2
3 is 3
4 is 4
5 is 5
Slice at 0 is 2
Slice at 1 is 3
Slice at 2 is 4
The length of arr1 is 6
The length of slice1 is 3
The capacity of slice1 is 4

三、用make()来创建一个切片

make 接受 2 个参数:元素的类型以及切片的元素个数。

var slice1 []type = make([]type, len)。

也可以简写为 

slice1 := make([]type, len)//len是元素长度

 make 的使用方式是:func make([]T, len, cap),其中 cap 是可选参数。

package main

import "fmt"

func main() {
	var slice1 []int = make([]int, 10)
	// load the array/slice:
	for i := 0; i < len(slice1); i++ {
		slice1[i] = 5 * i
	}

	// print the slice:
	for i := 0; i < len(slice1); i++ {
		fmt.Printf("Slice at %d is %d
", i, slice1[i])
	}
	fmt.Printf("
The length of slice1 is %d
", len(slice1))
	fmt.Printf("The capacity of slice1 is %d
", cap(slice1))
}

  输出:

Slice at 0 is 0
Slice at 1 is 5
Slice at 2 is 10
Slice at 3 is 15
Slice at 4 is 20
Slice at 5 is 25
Slice at 6 is 30
Slice at 7 is 35
Slice at 8 is 40
Slice at 9 is 45

The length of slice1 is 10
The capacity of slice1 is 10

3.1 new()和make()的区别

  • new(T) 为每个新的类型T分配一片内存,初始化为 0 并且返回类型为*T的内存地址:这种方法 返回一个指向类型为 T,值为 0 的地址的指针,它适用于值类型如数组和结构体(参见第 10 章);它相当于 &T{}
  • make(T) 返回一个类型为 T 的初始值,它只适用于3种内建的引用类型:切片、map 和 channel(参见第 8 章,第 13 章)。

换言之,new 函数分配内存,make 函数初始化

四、bytes包

原文地址:https://www.cnblogs.com/liubiaos/p/9371003.html