简体   繁体   中英

In Rust, Does Modifying a Borrowed Pointer Change the Original Value?

This is Rust 0.4

I believe it does, but it doesn't seem to be true for my particular use case.

I have an owned pointer to a vector of owned pointer to vector's.

I construct it as the following.

let mut table = ~[];
for [0, ..10].each |i| {
    let mut row = ~[];
    for [0, ..128].each |j| {
        row.push(A_CERTAIN_ENUM);
    }
    table.push(row);
}

Then, I pass this two dimensional vector to another function for further initialization.

The function looks something like this.

fn setT (table: &mut ~[~[SomeEnumType]]) {
    // Demonstration purposes...
    for [0, ..10].each |i| {
        for [0, ..128].each |j| {
            table[*i][*j] = A_DIFFERENT_ENUM;
        }
    }
}

I call the function with the following code.

setT(&table);

However, then upon inspection, the content of table is not changed at all! Everything inside is still A_CERTAIN_ENUM rather than A_DIFFERENT_ENUM .

Does anyone know how to have another function modify the parameter you pass to it?

Any help is appreciated!

Which version of Rust are you using? Didn't the type checker complain about using

setT(&mut table);

I am a little stumped too. Of course, pointers should work as expected!

Here is a working version of a similar code (rustc 0.5, commit 19f5f91):

enum Direction {
    North,
    East,
    South,
    West
}

fn main() {
    let mut table = ~[];
    for [0, ..10].each |i| {
        let mut row = ~[];
        for [0, ..128].each |j| {
            row.push(North);
        }
        table.push(copy row);
    }
    io::print(fmt!("before: %d\n", table[0][0] as int));
    setT(&mut table);
    io::print(fmt!("after: %d\n", table[0][0] as int));
}

fn setT(table: &mut ~[~[Direction]]) {
    for [0, ..10].each |i| {
        for [0, ..128].each |j| {
            table[*i][*j] = East;
        }
    }
}

Output:

before: 0
after: 1

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