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"
}
CodePudding user response:
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"
}