You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
933 B
48 lines
933 B
package main
|
|
|
|
import "fmt"
|
|
|
|
/**
|
|
定义切片
|
|
var slice1 []type = make([]type, len)
|
|
slice1 := make([]type, len)
|
|
指定容量,capacity
|
|
make([]T, length, capacity)
|
|
*/
|
|
|
|
func main() {
|
|
s := []int{1, 2, 3, 4}
|
|
s1 := make([]int, 2, 3)
|
|
fmt.Println(s)
|
|
fmt.Println(len(s1), cap(s1), s1)
|
|
fmt.Println(len(s), cap(s), s)
|
|
s2 := s[:3]
|
|
fmt.Println(s2)
|
|
|
|
|
|
var numbers []int
|
|
printSlice(numbers)
|
|
|
|
/* 允许追加空切片 */
|
|
numbers = append(numbers, 0)
|
|
printSlice(numbers)
|
|
|
|
/* 向切片添加一个元素 */
|
|
numbers = append(numbers, 1)
|
|
printSlice(numbers)
|
|
|
|
/* 同时添加多个元素 */
|
|
numbers = append(numbers, 2,3,4)
|
|
printSlice(numbers)
|
|
|
|
/* 创建切片 numbers1 是之前切片的两倍容量*/
|
|
numbers1 := make([]int, len(numbers), (cap(numbers))*2)
|
|
|
|
/* 拷贝 numbers 的内容到 numbers1 */
|
|
copy(numbers1,numbers)
|
|
printSlice(numbers1)
|
|
}
|
|
|
|
func printSlice(x []int){
|
|
fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)
|
|
} |