【发布时间】: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 的链接。