英文:
What is the Rust equivalent to append in Go?
问题
我正在尝试通过阅读文档来弄清楚如何将这个Go函数转换为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"
}
英文:
I am trying to figure out on my own reading through documentation, but with no luck on how to convert this Go function into 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"
}
This is not correct, at least the cards.append I know is wrong:
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"
}
答案1
得分: 11
你不能这样做。就像在Go语言中一样,Rust数组的大小是固定的。
在Rust中,类型[&str; 2]
大致相当于Go语言中的[2]string
,你也不能对其进行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"];
// 对于任何实现了`IntoIterator`的cards
cards.extend(additional_cards);
// 或者只对单张卡片进行操作
cards.push("Three of Hearts");
println!("{cards:?}")
}
fn new_card() -> &'static str {
"Five of Diamonds"
}
英文:
You can't. like in Go, Rust arrays are fixed size.
The type [&str; 2]
in Rust is roughly equivalent to [2]string
in Go, which you also can't append
to.
The closest to a Go slice you can get to in Rust is a Vec
which you can use like this:
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 `IntoIterator` 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"
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论