DEV Community

Roman
Roman

Posted on

A useful anti-pattern in Rust

There is newtype idiom often used in Rust, which gives more control over the data being processed.

Let's imagine a function that works with a list of users, but only if they are administrators, then instead of just passing an array of identifiers, it can be wrapped into newtype to make sure the data is correct:

struct Admins(Vec<u128>);
Enter fullscreen mode Exit fullscreen mode

Now it is possible to use this type:

fn print_admin_count(users: Admins) {
    println!("admins count: {}", users.0.len());
}
Enter fullscreen mode Exit fullscreen mode

This works, but it doesn't look as nice as if array was used directly users.len().

There are traits in Rust Deref/DerefMut that solve this problem, if we implement them for the wrapper type, then this will allow to work with the inner type directly:

impl Deref for Admins{
    //...
}

fn print_admin_count(users: Admins) {
    println!("admins count: {}", users.len());
}
Enter fullscreen mode Exit fullscreen mode

Full snippet

The documentation warns that these traits should be used only for smart pointers, although wider usage becomes more and more popular.

My links

I'm making my perfect todo, note-taking app Heaplist, you can try it here heaplist.app
And I have a twitter @rsk

Top comments (0)