码迷,mamicode.com
首页 > 移动开发 > 详细

go语言基础之append函数的使用

时间:2019-12-08 12:38:42      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:syntax   alt   int   printf   container   cell   print   add   number   

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)
}

#执行结果:

1
2
3
4
5
6
7
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函数的使用

标签:syntax   alt   int   printf   container   cell   print   add   number   

原文地址:https://www.cnblogs.com/qiaoyanlin/p/12005190.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!