Home > Net >  Returning a pointer to a boxed value from a collection in Rust
Returning a pointer to a boxed value from a collection in Rust

Time:01-30

I have a collection of boxed object:

objects : Vec<Box<MyObject>>

I have a function that needs to return a *mut MyObject, and it pretty much look like this.

    for object in self.objects.iter()
    {
        if object.name == new_object_name
        {
            return &mut *object;
        }
    }

    return std::ptr::null_mut();

But I am getting an error during compilation on return line:

expected struct `MyObject`, found struct `Box`

CodePudding user response:

You need to dereference twice, as object is &Box<MyObject>, and use iter_mut() because you want a mutable reference:

for object in self.objects.iter_mut() {
    if object.name == new_object_name {
        return &mut **object;
    }
}

return std::ptr::null_mut();
  • Related