在Go语言中,与append等价的Rust是什么?

7gcisfzg  于 2022-11-30  发布在  Go
关注(0)|答案(1)|浏览(130)

我正在尝试自己阅读文档,但没有找到如何将此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"
}

这是不正确的,至少卡。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"
}
rqmkfv5c

rqmkfv5c1#

你不能。就像在围棋里,Rust数组是固定大小的。
Rust中的类型[&str; 2]大致相当于Go语言中的[2]string,但你也不能将append转换为[2]string
在Rust中,最接近Go语言切片的是Vec,可以这样使用:

fn main() {
    let mut cards = vec!["Ace of Diamonds", new_card()];
    let additional_card: [&str; 1] = ["Six of Spades"];
    // for anything that implements `IntoIter` of cards
    cards.extend(additional_card);
    // or for a single card only
    cards.push("A single card");

    println!("{cards:?}")
}

fn new_card() -> &'static str  {
    "Five of Diamonds"
}

相关问题