append函数使用
1、使用append给切片添加数值
import "fmt"
func main() {
var sli []int
//使用append追加切片
sli = append(sli,1)
sli = append(sli,2)
fmt.Println(sli)
}
执行结果
[1 2]
2、append函数添加多个元素
import "fmt"
func main() {
var sli []int
//使用append追加切片
sli = append(sli,1,5)
fmt.Println(sli)
}
执行结果
[1 5]
3、使用append函数截取切片
//系统会截取切片sli下角标0-4的(不包含角标为4的数值)
import "fmt"
func main() {
var sli []int = []int{1,2,3,4,5,6,7,8,9}
//使用append追加切片
sli = append(sli[0:4])
fmt.Println(sli)
}
执行结果
[1 2 3 4]
4、使用append截取切片并赋值
//系统会截取切片sli下角标0-4的(不包含角标为4的数值),然后追加
import "fmt"
func main() {
var sli []int = []int{1,2,3,4,5,6,7,8,9}
//使用append追加切片
sli = append(sli[0:4],3,2,1)
fmt.Println(sli)
}
执行结果:
[1 2 3 4 3 2 1]
5、使用append函数对切片进行截取
//通过将切片切分成两个子切片然后赋值给切片
import "fmt"
func main() {
var sli []int = []int{1,2,3,4,5,6,7,8,9}
//使用append追加切片
sli = append(sli[0:4],sli[5:]...)
fmt.Println(sli)
}
执行结果:
[1 2 3 4 6 7 8 9]