简体   繁体   English

在Rust中,修改借用的指针会更改原始值吗?

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

This is Rust 0.4 这是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! 但是,检查后, table的内容完全没有改变! Everything inside is still A_CERTAIN_ENUM rather than A_DIFFERENT_ENUM . 内部的所有内容仍然是A_CERTAIN_ENUM而不是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? 您正在使用哪个版本的Rust? 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): 这是类似代码的工作版本(rustc 0.5,提交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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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