package main import "fmt" func main () { var team = [ . . . ] string { "hammer" , "soldier" , "mum" } fmt . Println ( team ) //[hammer soldier mum] for k , v : = range team { fmt . Println ( k , v ) } //0 hammer //1 soldier //2 mum a : = 2



package main

import "fmt"

func main() {
var team = [...]string{"hammer", "soldier", "mum"}
fmt.Println(team) //[hammer soldier mum]

for k, v := range team {
fmt.Println(k, v)
}
//0 hammer
//1 soldier
//2 mum

a := 2
b := 28
c := a + b
fmt.Println(c) // 30

var build [30]int
for i := 0; i < 30; i++ { //0 ~ 29
build[i] = i + 1
}

//切片全部整体
fmt.Println(build)
//[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30]
fmt.Println(build[:]) //与切片本身等效
fmt.Println(build[:len(build)]) //与切片本身等效
fmt.Println(build[:30]) //与切片本身等效

//部分
fmt.Println(build[5:10]) //[6 7 8 9 10]
fmt.Println(build[18:]) //[19 20 21 22 23 24 25 26 27 28 29 30]
fmt.Println(build[:2]) //[1 2]
fmt.Println(build[0:0]) //[] 空切片,一般用于切片复位
fmt.Println(build[0:1]) //[1]
fmt.Println(build[30:]) //[]

var numbers []int
for i := 0; i < 10; i++ {
numbers = append(numbers, i)
fmt.Printf("len: %d cap:%d pointer:%p \n", len(numbers), cap(numbers), numbers)
}
/*
len: 1 cap:1 pointer:0xc000016400
len: 2 cap:2 pointer:0xc000016410

len: 3 cap:4 pointer:0xc000014120
len: 4 cap:4 pointer:0xc000014120

len: 5 cap:8 pointer:0xc00001a100
len: 6 cap:8 pointer:0xc00001a100
len: 7 cap:8 pointer:0xc00001a100
len: 8 cap:8 pointer:0xc00001a100

len: 9 cap:16 pointer:0xc000102080
len: 10 cap:16 pointer:0xc000102080
*/

// 切片复制
//设置元素数量
const count = 10
//预分配足够多的元素切片
srcData := make([]int, count)

//将切片赋值
for i := 0; i < count; i++ {
srcData[i] = i
}

//引用切片数据
refData := srcData

//预分配足够多的元素切片
copyData := make([]int, count)

//将数据分配到新的切片空间copyData中
copy(copyData, srcData)
fmt.Println(copyData, refData) //[0 1 2 3 4 5 6 7 8 9] [0 1 2 3 4 5 6 7 8 9]

//修改原始数据的第一个元素
srcData[0] = 999

//打印复制切片的第一个和最后一个元素;复制数据不变,原始数据改变
fmt.Println(copyData[0], copyData[count-1], copyData, refData)
//0 9 [0 1 2 3 4 5 6 7 8 9] [999 1 2 3 4 5 6 7 8 9]

copy(copyData, srcData[4:6])
fmt.Println(copyData, refData,srcData)
//[4 5 2 3 4 5 6 7 8 9] [999 1 2 3 4 5 6 7 8 9][999 1 2 3 4 5 6 7 8 9]

for i := 0; i < 5; i++ {
fmt.Printf("i= %d v= %d \n",i,copyData[i])// 4 5 2 3 4 %
}

//删除元素
seq:=[]string{"a","b","c","d","e","f"}
//指定删除位置
delIndex:=2
//查看删除前和之后的元素
fmt.Println(seq[:delIndex],seq[delIndex+1:])
//[a b] [d e f]
//将删除前后的元素连接起来
seq=append(seq[:delIndex],seq[delIndex+1:]...)
fmt.Println(seq)// [a b d e f]

}


【文章转自阿里云服务器代理商 http://www.558idc.com/aliyun.html 复制请保留原URL】