Marcus Buffett
Marcus Buffett

Reputation: 1389

How to mutate field in struct within a pointer?

If I have a variable of type P<SomeStruct> (owned, or a mutable reference), is it possible to mutate a field on that struct, without returning a new pointer? I've been trying something like this:

#![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()
}

but of course that fails with:

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

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

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

Upvotes: 0

Views: 413

Answers (1)

trent
trent

Reputation: 27885

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

Sure, here's an example using 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()
}

But you seem to be trying to do that with syntax::ptr::P, which self-describes as a frozen owned smart pointer:

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

To be more specific, P<T> implements Deref, but not DerefMut, so you can't get a &mut T out of a &mut P<T> by dereferencing it.

Upvotes: 4

Related Questions