在Go中,有make
和append
函数,第一个让你创建一个指定类型,长度和容量的切片,而第二个让你将一个元素附加到指定的切片。它或多或少与这个玩具示例相似:
func main() {
// Creates a slice of type int, which has length 0 (so it is empty), and has capacity 5.
s := make([]int, 0, 5)
// Appends the integer 0 to the slice.
s = append(s, 0)
// Appends the integer 1 to the slice.
s = append(s, 1)
// Appends the integers 2, 3, and 4 to the slice.
s = append(s, 2, 3, 4)
}
Rust是否提供与切片一起使用的类似功能?
没有。
Go和Rust切片是不同的:
因此,您无法使用Rust切片从基础容器中插入,追加或删除元素。相反,你需要:
注意:Rust std
不像Java那样为它的集合提供trait
抽象,但是如果你认为对于特定问题它是值得的,你仍然可以自己创建一些。