gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:22:06 25 4
gpt4 key购买 nike

在 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 是否提供类似的功能来处理切片?

最佳答案

没有。

Go 和 Rust 切片不同:

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

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

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

注意:与 Java 不同,Rust std 不为其集合提供 trait 抽象,但如果您认为值得,您仍然可以自己创建一些一个特定的问题。

关于rust - 在 Rust 中创建一个切片并附加到它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48007342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com