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.)
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"); }
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With