Reputation: 2479
fn function_name(the_list: ?) {
// do something
println!("{}",the_list);
}
fn main() {
let data = [5,20,18,30,9,7,12,40]; // where data size is n
let result = function_name(&data);
}
I have a very simple function here which I want to pass a list of size n into. I have looked through the docs and only found solutions for lists whose size is known which is not what I want.
How do I approach this problem?
Upvotes: 0
Views: 445
Reputation: 10882
To get compile time information about the size of passed array you can use const generics, like this:
fn function_name<T:Debug, const N: usize>(the_list: &[T; N]) {
// do something
println!("{:?}", the_list);
}
fn main() {
let data = [5,20,18,30,9,7,12,40]; // where data size is n
let result = function_name(&data);
}
If you want to restrict this size to particular value, you can do this:
fn function_name<T:Debug>(the_list: &[T; 8]) {
P.S., [i32]
is called primitive array.
Upvotes: 4
Reputation: 2479
fn function_name(the_list: &[i32]) {
// do something
println!("{:?}",the_list);
}
fn main() {
let data = [5,20,18,30,9,7,12,40]; // where data size is n
let result = function_name(&data);
}
//output: [5, 20, 18, 30, 9, 7, 12, 40]
The solution is to have the function accept a general [i32] list type instead. It is not necessary to write the length of the list's input if the input is of size n.
Upvotes: 3