Home > Article > Backend Development > What is Rust's equivalent of append in Go?
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.
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" }
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" }
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" }
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!