DEV Community

Roman
Roman

Posted on

1

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay