1. 程式人生 > >go語音基礎之append函數的使用

go語音基礎之append函數的使用

clas imp lse 末尾 light %d end ack 添加元素

1、append函數的使用

作用:在原切片的末尾添加元素

示例:

package main //必須有個main包

import "fmt"

func main() {
	s1 := []int{}
	fmt.Printf("len = %d, cap = %d\n", len(s1), cap(s1))
	fmt.Println("s1 = ", s1)

	//在原切片的末尾添加元素
	s1 = append(s1, 1)
	s1 = append(s1, 2)
	s1 = append(s1, 3)
	fmt.Printf("len = %d, cap = %d\n", len(s1), cap(s1))
	fmt.Println("s1 = ", s1)

	s2 := []int{1, 2, 3}
	fmt.Println("s2 = ", s2)
	s2 = append(s2, 5)
	s2 = append(s2, 5)
	s2 = append(s2, 5)
	fmt.Println("s2 = ", s2)
}

#執行結果:

len = 0, cap = 0
s1 =  []
len = 3, cap = 4
s1 =  [1 2 3]

s2 =  [1 2 3]
s2 =  [1 2 3 5 5 5]

  

  

go語音基礎之append函數的使用