【问题标题】:How to mutate field in struct within a pointer?如何在指针内改变结构中的字段?
【发布时间】:2017-05-22 16:16:49
【问题描述】:

如果我有一个P<SomeStruct> 类型的变量(拥有或可变引用),是否可以在不返回新指针的情况下改变该结构上的字段?我一直在尝试这样的事情:

#![feature(rustc_private)]

extern crate syntax;

use syntax::ptr::P;

#[derive(Debug)]
struct Baz {
    id: String,
}

#[test]
fn foo() {
    let mut pointer = P(Baz { id: "blah".to_string() });
    bar(&mut pointer);
}

fn bar(x: &mut P<Baz>) {
    x.id = "bing".to_string()
}

但当然会失败:

error: cannot assign to immutable field
   --> src/lib.rs:116:5
    |
116 |     x.id = "bing".to_string()
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^ cannot mutably borrow immutable field

有什么方法可以在智能指针内改变结构上的字段?

游乐场网址:https://play.rust-lang.org/?gist=5675bc2ef4297fe691204a69ffc19461&version=nightly&backtrace=0

【问题讨论】:

  • 这是不可重现的。考虑在Rust Playground 中写一个例子来显示这个确切的编译错误。
  • @E_net4,我添加了必要的导入和功能标志,以及 rust playground 的链接。

标签: pointers struct rust


【解决方案1】:

有什么方法可以在智能指针内改变结构上的字段?

当然,这是一个使用Box (playground) 的示例:

#[derive(Debug)]
struct Baz {
    id: String,
}

#[test]
fn foo() {
    let mut pointer = Box::new(Baz { id: "blah".to_string() });
    bar(&mut pointer);
}

fn bar(x: &mut Box<Baz>) {
    x.id = "bing".to_string()
}

但您似乎正在尝试使用syntax::ptr::P 来做到这一点,它自我描述为frozen owned smart pointer

  • 不变性P&lt;T&gt; 不允许改变其内部 T,这与 Box&lt;T&gt; 不同 [...]

更具体地说,P&lt;T&gt; 实现了Deref,但不是DerefMut,因此您无法通过取消引用从&amp;mut P&lt;T&gt; 中获得&amp;mut T

【讨论】:

    猜你喜欢
    • 2019-07-10
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多