猿问

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

我正在学习一个教程来学习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值”。


如果您想查看完整的代码,请在此要点中。


炎炎设计
浏览 110回答 2
2回答

慕沐林林

在此处检查追加定义。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])

慕哥6287543

// 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因此,您只能追加元素,而不能追加整个切片。
随时随地看视频慕课网APP

相关分类

Go
我要回答