首頁  >  文章  >  後端開發  >  Rust 相當於 Go 中的append 是什麼?

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

WBOY
WBOY轉載
2024-02-09 10:24:32316瀏覽

Rust 相当于 Go 中的append 是什么?

php小編西瓜在這裡為大家解答一個問題:「Rust 相當於Go 中的append 是什麼?」Rust 是一種系統級程式語言,而Go 是一種並發程式語言。在 Rust 中,相當於 Go 中的 append 函數的功能是使用 Vec 類型的 push 方法。 Vec 是 Rust 標準庫中的動態數組類型,使用 push 方法可以在數組的末端添加元素。這種功能類似於 Go 中的 append 函數,但是在 Rust 中需要使用 Vec 的 push 方法實作。透過這種方式,Rust 提供了一種簡單且靈活的方式來操作動態陣列。

問題內容

我試圖透過自己閱讀文件來弄清楚,但對於如何將此 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"
}

解決方法

你不能。就像在 go 中一樣,rust 陣列是固定大小的。

類型 [&str; 2]rust 中的 大致相當於 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"];
    // 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"
}

以上是Rust 相當於 Go 中的append 是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除