Rust中与Go中的append等效的函数是什么?

huangapple go评论84阅读模式
英文:

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"
}

huangapple
  • 本文由 发表于 2022年11月29日 05:11:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/74606494.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定