How to properly create a new Vec inside a function and return it for later use

Here is the code:

fn read_chunk_data(selected_world: String, size: usize, chunk_vec: Vec<Vec<char>>) -> Vec<Vec<char>> { 
    let mut chunk_file = fs::File::open(selected_world).unwrap();
    let mut buf_reader = BufReader::new(chunk_file);
    let mut contents = String::new();
    buf_reader.read_to_string(&mut contents).unwrap();

    let mut chunk: Vec<char> = contents.chars().collect();

    for o in 1..chunk.len() / (size * size) {
        chunk_vec.push(main_chunk[(size * size) * o..(size * size) * o + (size * size)].to_vec());  
    return chunk_vec;

I am rather new to Functions/Pointer, I tried using &mut, but it leads down this rabbit hole, because it requires Me to use .to_vec() when returning, which turns My 2d Vector into a 1d vector. And I need it to stay as a 2d vector. Is there some Syntax/Standard Library feature that I do not know about?

If in your function you receive a mutable reference (&mut) to a Vec, then you are not returning that vector, you are mutating it.

You need to either change the signature and i.e. return the Unit type (()) or return a completely new vector, which is the preferred way in functional programming.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.