0

I am trying to write a generic function to pick up a random element in a vector of any kind. How can I specify an arbitrary vector type?

For example:

let list1: Vec<u32> = vec![1, 2, 3];
let list2: Vec<&str> = vec!["foo", "bar"];

fn print_a_random_element(a_list: Vec<?????>) {
    // do some stuff
}

print_a_random_element(list1); // get error
print_a_random_element(list2); // get error
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Col
  • 71
  • 7
  • 2
    You will be well-served to completely read [*The Rust Programming Language*](https://doc.rust-lang.org/book/). For example, [chapter 10](https://doc.rust-lang.org/book/ch10-00-generics.html). – Shepmaster Oct 29 '19 at 18:46
  • 1
    Yeap I know the book and I read it but rust is a complexe language and it's easy to forget some syntax rules. Anyway thanks for this reminder. – Col Oct 29 '19 at 18:57

1 Answers1

2

Generic types specific to a function are declared using the <> syntax on the function definition:

fn print_a_random_element<T>(a_list: Vec<T>) {
    // do some stuff
}

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366