简体   繁体   中英

How do I pass a Vec<Vec<i32>> to a function?

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())
}

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())
    }
}

playground

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())
    }
}

playground

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())
}

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);
}

Playground

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM