Col
Col

Reputation: 71

How to use an arbitrary type as a function argument?

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

Upvotes: 0

Views: 854

Answers (1)

Shepmaster
Shepmaster

Reputation: 432139

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:

Upvotes: 2

Related Questions