gpt4 book ai didi

pointers - 如何在指针内改变结构中的字段?

转载 作者:行者123 更新时间:2023-11-29 08:23:46 25 4
gpt4 key购买 nike

如果我有一个 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

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

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

最佳答案

Is there any way to mutate a field on a struct within a smart pointer?

当然,这是一个使用 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 :

  • Immutability: P<T> disallows mutating its inner T, unlike Box<T> [...]

更具体地说,P<T>工具 Deref , 但不是 DerefMut , 所以你不能得到 &mut T从一个&mut P<T>通过取消引用它。

关于pointers - 如何在指针内改变结构中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44117647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com