千恋*万花

  • 首页
  • 个人简历
  • 文章分类
    • 后端开发
    • 运维
    • 基础知识
    • 笔记
    • 工作运维记录
    • 随笔
    • 未分类文章
  • 管理
    • 后台管理
    • 登出
萌奈の笔记簿
分享我的努力,希望为你助力
  1. 首页
  2. 后端开发
  3. golang
  4. 正文

Golang append() 切片 追加 切片

2020-09-14 2764点热度 0人点赞 0条评论

Golang append() 切片 追加 切片

在程序中,有时候需要在切片后面再追加一个切片,比如在执行以下代码的时候

a := []int{1, 2, 3}
b := []int{9, 8, 7}
a = append(a, b)

会遇到 Cannot use 'b' (type []int) as type int 的问题。

根据错误提示,我们很明显能发现是数据类型错误了。

直接上解决办法

将第三行append语句改为 append(a, b...) 即可。注意那三个点

根据官方文档:

Package:
builtin
func append(slice []Type, elems ...Type) []Type
The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice. It is therefore necessary to store the result of append, often in the variable holding the slice itself:
slice = append(slice, elem1, elem2)
slice = append(slice, anotherSlice...)
As a special case, it is legal to append a string to a byte slice, like this:
slice = append([]byte("hello "), "world"...)

我们知道 append 函数有两种用法:

  1. append(slice, elem1, elem2) append(原切片, 元素1, 元素2)
  2. append(slice, anotherSlice...) append(原切片, 另一个切片 ...) 这三个点就很有魔性了,它的作用是把原切片打散,然后分别当做参数传入形参中。
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
标签: Golang 心得 学习心得
最后更新:2023-02-06

初音萌奈

我是练习时长 一年半 的后端开发程序员 谢谢你参观我的博客! 本网站现已支持IPv6 ☞ 个人简历 ☜

点赞
下一篇 >
文章目录
  • Golang append() 切片 追加 切片
    • 直接上解决办法

COPYRIGHT © 2023 HatsuneMona ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

晋ICP备17007130号-4