Reputation: 730
Given a 2D vector of i32
s:
let v = vec![
vec![1, 1, 1],
vec![0, 1, 0],
vec![0, 1, 0],
];
How can I pass it to a function to ultimately print its details? I tried:
fn printVector(vector: &[[i32]]) {
println!("Length{}", vector.len())
}
Upvotes: 3
Views: 2470
Reputation: 8476
You may use a function which accepts a slice of T
where T
can also be referenced as a slice:
fn print_vector<T>(value: &[T])
where
T: AsRef<[i32]>,
{
for slice in value {
println!("{:?}", slice.as_ref())
}
}
If you want to accept any type instead of just i32
, you can also generalize this:
fn print_vector<T, D>(value: &[T])
where
T: AsRef<[D]>,
D: Debug,
{
for slice in value {
println!("{:?}", slice.as_ref())
}
}
Upvotes: 8
Reputation: 370
fn printVector(vector: &Vec<Vec<i32>>) {
println!("Length{}", vector.len())
}
let v = vec![
vec![1, 1, 1],
vec![0, 1, 0],
vec![0, 1, 0],
];
printVector(&v);
In this example, &Vec<Vec<i32>
and &[Vec<i32>]
are no different; maybe you want to change to this:
fn print_vector(vector: &[Vec<i32>]) {
for i in vector {
for j in i {
println!("{}", j)
}
}
}
let v = vec![
vec![1, 1, 1],
vec![0, 1, 0],
vec![0, 1, 0],
];
print_vector(&v);
Upvotes: 1
Reputation: 15045
Since you're going to pass vectors to your function, the following code should work:
fn print_vector(vector: Vec<Vec<i32>>) {
println!("Length{}", vector.len())
}
Upvotes: 5
Reputation: 1359
You need to pass a slice of vectors - &[Vec<i32>]
, not a slice of slices:
fn print_vector(vector: &[Vec<i32>]) {
println!("Length {}", vector.len())
}
fn main() {
let v = vec![vec![1, 1, 1], vec![0, 1, 0], vec![0, 1, 0]];
print_vector(&v);
}
Upvotes: 3