0

In Go I can declare a new EMPTY slice using:

players := make([]Player, 0, len(player_list))

How to do this in Rust?

I tried with:

players = vec!(Player; 0; player_list.len())

but this is wrong because I only need to declare an empty array, not new one with one Player already inside.

How to?

Fred Hors
  • 3,258
  • 3
  • 25
  • 71
  • You should probably directly use the `Vec` type and not the `vec!` macro. – Stéphane Veyret Nov 12 '22 at 10:09
  • 5
    If I am not mistaken (I am very new to rust), if you want to create a new empty vector with already allocated space for your players, you should use : `players = Vec::with_capacity(player_list.len())` – Stéphane Veyret Nov 12 '22 at 10:13
  • How? I would like to understand how to add an element after the declaration too... – Fred Hors Nov 12 '22 at 10:13
  • 2
    To add elements after declaration, you can use `players.push(player)`. – Stéphane Veyret Nov 12 '22 at 10:15
  • @StéphaneVeyret is completely correct. That aside the `vec![]` invocation makes no sense, `vec!` just takes a value and a length, it doesn't need a type. You also need `let players` to declare that variable. – Masklinn Nov 12 '22 at 10:17
  • 1
    Does this answer your question? [Create an empty vector of size n, and not fill it with anything](https://stackoverflow.com/questions/71989694/create-an-empty-vector-of-size-n-and-not-fill-it-with-anything) – Mate Nov 12 '22 at 10:17
  • @Mate they don't actually want a vector of *length* n, Go's `make` takes a length and a capacity, if the length is nonzero, the array gets filled with zero-values. Here the length is 0: `players := make(/*[]T*/[]Player, /*length*/0, /*capacity*/len(player_list))` so it's just preallocating. – Masklinn Nov 12 '22 at 10:20

1 Answers1

2

First of all, array is not a vector and zero-sized array would be similar to (), so I guess you need vectors. To create an empty vector use Vec::new like this:

let mut players = Vec::<Player>::new();

To create a vector with custom capacity use Vec::with_capacity.

Miiao
  • 751
  • 1
  • 8