Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the Rust equivalent to append in Go?

I am trying to figure out on my own reading through documentation, but with no luck on how to convert this Go function into 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"
}

This is not correct, at least the cards.append I know 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"
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t. like in Go, Rust arrays are fixed size.

The type [&str; 2] in Rust is roughly equivalent to [2]string in Go, which you also can’t append to.

The closest to a Go slice you can get to in Rust is a Vec which you can use like this:

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

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading