Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create new instances of a wrapped vector in Rust?

Tags:

types

rust

I'd like to create my own vector struct, so I can attach extra methods.

pub struct MyStructVec(pub Vec<MyStruct>);

Having done this, how would a new instance of this vector be created?

MyStructVec::new() isn't recognized. How would existing vector creation methods be used with this type? (new, with_capacity... etc.)

like image 519
ideasman42 Avatar asked Oct 29 '25 16:10

ideasman42


2 Answers

A newtype "hides" its internals. You do not get transparent access to the interior. To create a new object of MyStructVec, you need to call the inner type's constructor and then wrap it:

MyStructVec(Vec::new())

MyStructVec(Vec::with_capacity(42))

After the creation of such an object, you can use the object somewhat transparently by implementing Deref and DerefMut for your type:

impl std::ops::Deref for MyStructVec {
    type Target = Vec<MyStruct>;
    fn deref(&self) -> &Vec<MyStruct> {
        &self.0
    }
}

impl std::ops::DerefMut for MyStructVec {
    fn deref_mut(&mut self) -> &mut Vec<MyStruct> {
        &mut self.0
    }
}

so I can attach extra methods

That's not the way newtypes are used. Newtypes are used for type safety. If all you want is that all Vec<MyStruct> have new methods, create an extension trait:

trait VecMyStructExt {
    fn foo(&self);
}
impl VecMyStructExt for Vec<MyStruct> {
    fn foo(&self) { println!("foo"); }
}
like image 72
oli_obk Avatar answered Oct 31 '25 11:10

oli_obk


MyStructVec::new() isn't recognized.

Indeed, because you've defined a new type but not defined any methods yet. You can do so easily:

impl MyStructVec {
    pub fn new() -> MyStructVec {
        MyStructVec(Vec::new())
    }
}

but as said well in the other answer you don't get the wrapped type's methods directly on your new struct directly, so you'd need to wrap the ones you want. (In some cases you might be able to automate to some extent it using macros)

like image 41
Chris Emerson Avatar answered Oct 31 '25 12:10

Chris Emerson