创建一个切片并在Rust中附加到它

问题描述 投票:0回答:1

在Go中,有makeappend函数,第一个让你创建一个指定类型,长度和容量的切片,而第二个让你将一个元素附加到指定的切片。它或多或少与这个玩具示例相似:

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
1个回答
7
投票

没有。

Go和Rust切片是不同的:

  • 在Go中,切片是另一个容器的代理,允许观察和改变容器,
  • 在Rust中,切片是另一个容器中的视图,因此只允许观察容器(尽管它可以允许改变单个元素)。

因此,您无法使用Rust切片从基础容器中插入,追加或删除元素。相反,你需要:

  • 使用容器本身的可变引用,
  • 设计一个特征并使用对所述特征的可变引用。

注意:Rust std不像Java那样为它的集合提供trait抽象,但是如果你认为对于特定问题它是值得的,你仍然可以自己创建一些。

© www.soinside.com 2019 - 2024. All rights reserved.