在Rust中创建切片并将其附加到其中

3
在Go语言中,有两个函数makeappend。其中,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是否提供类似的功能来处理切片?

Rust 中的切片本质上不是直接创建的,而是从现有变量中创建的。请查看 Vec::with_capacity。 - Mad Matts
1个回答

18

编号。

Go和Rust的切片是不同的:

  • 在Go中,切片是另一个容器的代理,允许同时观察和修改容器,
  • 在Rust中,切片是另一个容器中的视图,因此仅允许观察容器(虽然它可能允许修改单个元素)。

因此,您不能使用Rust切片从底层容器中插入、追加或删除元素。相反,您需要:

  • 使用对容器本身的可变引用,
  • 设计一个trait并使用对该trait的可变引用。

注意:Rust std未为其集合提供trait抽象,不像Java,但如果您认为对于特定问题值得创建,则仍可以自己创建一些。


感谢您的澄清。 - tinker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接