var slice []type = make([]type, len)
slice := make([]type, len)
slice := make([]type, len, cap)
从数组中截取出切片:
var a = [5]int{1,2,3,4,5}
fmt.Println(a)
//切片引用传值
var b = a[1:]
fmt.Println(b)
b[0] = 666
fmt.Println(a)
fmt.Println(b)
输出:
[1 2 3 4 5]
[2 3 4 5]
[1 666 3 4 5]
[666 3 4 5]
用append内置函数操作切片:
slice = append(slice, 10)
var a = []int{1,2,3}
var b = []int{4,5,6}
a = append(a, b…)
For range 遍历切片:
for index, val := range slice {
}
切片resize:
var a = []int {1,3,4,5}
b := a[1:2]
b = b[0:3]
切片拷贝:
s1 := []int{1,2,3,4,5}
s2 := make([]int, 10)
copy(s2, s1)
s3 := []int{1,2,3}
s3 = append(s3, s2…)
s3 = append(s3, 4,5,6)
string与slice,string底层就是一个byte的数组,因此,也可以进行切片操作:
str := “hello world”
s1 := str[0:5]
fmt.Println(s1)
s2 := str[5:]
fmt.Println(s2)
如何改变string中的字符值?string本身是不可变的,因此要改变string中字符,需要如下操作:
str := “hello world”
s := []byte(str)
s[0] = ‘o’
str = string(s)
package main
import "fmt"
func main() {
slice := []int {10, 20, 30, 40, 50}
fmt.Println(slice)
newSlice := slice[1:3]
newSlice[1] = 88
fmt.Println(newSlice)
fmt.Println(slice)
fmt.Println(newSlice[1])
newSlice = append(newSlice, 666, 888)
fmt.Println(newSlice)
fmt.Println(newSlice[2])
fmt.Println()
fmt.Println()
fmt.Println()
//如果不加第三个索引,由于剩余的所有容量都属于 slice,向slice 追加Kiwi 会改变原有底层数组索引为3 的元素的值Banana。不过在代码清单4-36 中我们限制了slice 的容量为1。当我们第一次对slice 调用append 的时候,会创建一个新的底层数组,这个数组包括2 个元素,并将水果Plum 复制进来,再追加新水果Kiwi,并返回一个引用了这个底层数组的新切片:
// 创建字符串切片
// 其长度和容量都是5 个元素
source := []string{"Apple", "Orange", "Plum", "Banana", "Grape"}
// 对第三个元素做切片,并限制容量
// 其长度和容量都是1 个元素
newSlice2 := source[2:3:3]
fmt.Println(source)
// 向slice 追加新字符串
newSlice2 = append(newSlice2, "Kiwi")
fmt.Println(source)
fmt.Println(newSlice2)
}
输出:
[10 20 30 40 50]
[20 88]
[10 20 88 40 50]
88
[20 88 666 888]
666
[Apple Orange Plum Banana Grape]
[Apple Orange Plum Banana Grape]
[Plum Kiwi]
Process finished with exit code 0
转载于:https://blog.51cto.com/5660061/2346142