[英]What is the Rust equivalent to append in Go?
我试图通过自己阅读文档来弄清楚,但没有运气如何将这个 Go function 转换为 Rust:
func main() {
cards := []string{"Ace of Diamonds", newCard()}
cards = append(cards, "Six of Spades")
fmt.Println(cards)
}
func newCard() string {
return "Five of Diamonds"
}
这是不正确的,至少 cards.append 我知道是错误的:
fn main() {
let mut cards: [&str; 2] = ["Ace of Diamonds", new_card()];
let mut additional_card: [&str; 1] = ["Six of Spades"];
cards.append(additional_card);
println!("cards")
}
fn new_card() -> &'static str {
"Five of Diamonds"
}
你不能。 像 Go 一样,Rust arrays 是固定大小。
类型[&str; 2]
[&str; 2]
in Rust 大致相当于[2]string
in Go,你也不能append
到。
您可以在 Rust 中获得的最接近 Go 切片的是一个Vec
,您可以像这样使用它:
fn main() {
let mut cards = vec!["Ace of Diamonds", new_card()];
let additional_cards: [&str; 2] = ["Six of Spades", "Seven of Clubs"];
// for anything that implements `IntoIter` of cards
cards.extend(additional_cards);
// or for a single card only
cards.push("Three of Hearts");
println!("{cards:?}")
}
fn new_card() -> &'static str {
"Five of Diamonds"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.