Hi, I have a struct with a field that needs to be mutable. I don't want to have to rewrite the entire struct, but it needs to be able to hold either a &mut T
or a T
.
I have tried this:
pub struct Foo<T, M: AsMut<T>> {mut_ref: M};
but the issue is that AsMut<T>
isn't implemented for all T.
I could also do this:
struct RefFoo<'t, T> { // The actual implementation is given to this struct
bar: &'t mut T
}
struct Foo<'t, T> {
owned: T,
bar: RefFoo<'t, T>,
}
fn main() {
let owned = String::new();
let bar = RefFoo {bar: &mut owned};
let foo = Foo {
owned,
bar,
};
}
However the issue here is that Foo
contains both the owned and the mutable reference, which isn't allowed per Rust's ownership rules.
I have also tried:
pub trait AsMut {
fn as_mut(&mut self) -> &mut Self;
}
impl<T> AsMut for T {...}
impl<T> AsMut for &mut T {...}
But I get an error that says these implementations could possibly overlap