0

Can I have a mutable reference to a value and a mutable reference to a trait object of the same value inside the same scope? Is that undefined behavior? An example code snippet is added below for clarification.

In the below code is it valid to have the check and check_trait references at the same time.

pub trait fire {
    fn hi(&self);
}

struct foo {
    bar: isize,
}

impl foo {
    fn new(x: isize) -> Self {
        foo { bar: x }
    }
}
impl fire for foo {
    fn hi(&self) {
        println!("hi");
    }
}

fn main() {
    let mut init = Box::new(foo::new(1));

    let leaked = Box::into_raw(x);
    let check = unsafe { leaked.as_mut().unwrap() };

    let mut trait_object:Box<dyn fire> = unsafe {
        Box::from_raw(leaked)
    };
    let check_trait = &mut trait_object;

    println!("{}", check.bar);
    check_trait.hi(5);
}
E_net4
  • 27,810
  • 13
  • 101
  • 139
  • Side note: [prefer UpperCamelCase for type names such as structs and traits](https://rust-lang.github.io/api-guidelines/naming.html) – E_net4 Oct 06 '21 at 15:15
  • 2
    As per the linked question: _"Multiple mutable aliases are undefined behavior."_ That the other reference is a trait object is orthogonal to the problem, since they are still aliased. See also: https://stackoverflow.com/questions/58364807/why-rust-prevents-from-multiple-mutable-references – E_net4 Oct 06 '21 at 15:18
  • You have used two unsafe blocks here. This means you are now responsible for the proper handling of whatever restrictions of safe rust you broke here. Rust's guarantees will no longer protect you. It is why it made you type in the unsafe blocks. This code is syntactically valid. In order for it to be well behaved, you will need to think carefully about how the memory is managed when the pointers get out of scope. – Kendas Oct 06 '21 at 15:23
  • Yep yep i am aware of the contracts that one needs to maintain when using unsafe code. My source of confusion is the trait objects part, whether the type casting to a trait object violates the contract or not. But as @E_net4thecurator said that this will be UB even if its a trait object reference and I think that answers my question. Thanks! – Abishek0398 Oct 06 '21 at 15:31

0 Answers0