What is Rust's equivalent of append in Go?

WBOY
Release: 2024-02-09 10:24:32
forward
353 people have browsed it

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

php editor Xigua is here to answer a question for everyone: "What is Rust equivalent to append in Go?" Rust is a system-level programming language, and Go is a Concurrent programming language. In Rust, the functional equivalent of the append function in Go is to use the push method of the Vec type. Vec is a dynamic array type in the Rust standard library. Use the push method to add elements to the end of the array. This function is similar to the append function in Go, but in Rust it needs to be implemented using the push method of Vec. In this way, Rust provides a simple and flexible way to manipulate dynamic arrays.

Question content

I tried to figure it out by reading the documentation myself but had no luck on how to convert this go function to 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"
}
Copy after login

This is incorrect, at least I know of cards.append which 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"
}
Copy after login

Solution

You can't. Just like in go, rust arrays are fixed size.

Type [&str; 2] in rust is roughly equivalent to [2]string in go, but you can't append it either.

In rust, the closest thing to go slicing is 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"
}
Copy after login

The above is the detailed content of What is Rust's equivalent of append in Go?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!