为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我们在这个追加函数调用中需要三个点?

为什么我们在这个追加函数调用中需要三个点?

Go
炎炎设计 2022-08-24 17:28:05
我正在学习一个教程来学习Go中的Rest API。有这段代码。func removeBook(w http.ResponseWriter, r *http.Request) {    params := mux.Vars(r)    id, _ := strconv.Atoi(params["id"])    for i, item := range books {        if item.ID == id {            books = append(books[:i], books[i+1:]...)        }    }}特别是这部分。books = append(books[:i], books[i+1:]...)OK,将一个或多个项追加到切片(在本例中为结构切片)。 获取从开始到 的所有内容,不包括 。然后表示后面的下一项,在右侧添加冒号表示从那里到结束的所有内容。因此,这意味着我们将所有项目都保留到排除,然后在 之后获取所有项目。这意味着我们正在排除/删除 ,这就是功能点。appendbooksbookbooks[:i]iii+1iiiiiremoveBook我有这么多的逻辑,但是这三个点在那里做什么?我知道可变参数函数中使用了三个点,但是为什么在这个追加函数中我们需要三个点呢?当我删除这3个点时,我的编辑说“不能使用books[i + 1:](类型[]Book的值)作为要追加的参数中的Book值”。如果您想查看完整的代码,请在此要点中。
查看完整描述

2 回答

?
慕沐林林

TA贡献2016条经验 获得超9个赞

在此处检查追加定义。

func append(slice []Type, elems ...Type) []Type

在第二个论点中,它接受多个“elems”。

在您给出的示例中,它实质上是将元素作为逗号分隔的参数列表进行传递

假设书的长度是10,而我是7。然后,它传递切片中的前 7 个元素(项 0 到 6),然后作为逗号分隔的列表传递第 8 个和第 9 个元素。

books = append(books[:i], books[i+1:]...)

其实是

 books = append(books[:7], books[8], books[9])


查看完整回答
反对 回复 2022-08-24
?
慕哥6287543

TA贡献1831条经验 获得超10个赞

// 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"...)

func append(slice []Type, elems ...Type) []Type

因此,您只能追加元素,而不能追加整个切片。


查看完整回答
反对 回复 2022-08-24
  • 2 回答
  • 0 关注
  • 109 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号