Heim  >  Artikel  >  Backend-Entwicklung  >  Was ist Rusts Äquivalent zum Anhängen in Go?

Was ist Rusts Äquivalent zum Anhängen in Go?

WBOY
WBOYnach vorne
2024-02-09 10:24:32317Durchsuche

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

php-Editor Xigua ist hier, um eine Frage für alle zu beantworten: „Was ist das Äquivalent von Rust zum Anhängen in Go?“ Rust ist eine Programmiersprache auf Systemebene und Go ist eine gleichzeitige Programmiersprache. In Rust besteht das funktionale Äquivalent der Append-Funktion in Go darin, die Push-Methode vom Typ Vec zu verwenden. Vec ist ein dynamischer Array-Typ in der Rust-Standardbibliothek. Verwenden Sie die Push-Methode, um Elemente am Ende des Arrays hinzuzufügen. Diese Funktion ähnelt der Append-Funktion in Go, muss jedoch in Rust mit der Push-Methode von Vec implementiert werden. Auf diese Weise bietet Rust eine einfache und flexible Möglichkeit, dynamische Arrays zu manipulieren.

Frageninhalt

Ich habe versucht, es herauszufinden, indem ich die Dokumentation selbst gelesen habe, aber kein Glück, wie ich diese Go-Funktion in Rust umwandeln kann:

func main() {
  cards := []string{"ace of diamonds", newcard()}
  cards = append(cards, "six of spades")

  fmt.println(cards)
}

func newcard() string {
  return "five of diamonds"
}

Das ist falsch, zumindest das mir bekannte Cards.append ist falsch:

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

Lösung

Das geht nicht. Genau wie in Go haben Rust-Arrays eine feste Größe.

Typ [&str; 2]rust 中的 大致相当于 go 中的 [2]string,但你也不能对其进行 append .

Bei Rost kommt dem Schneiden am nächsten vec, das Sie wie folgt verwenden können:

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

Das obige ist der detaillierte Inhalt vonWas ist Rusts Äquivalent zum Anhängen in Go?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:stackoverflow.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen