簡體   English   中英

Go中的Rust相當於append是什么?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM