[New to Rust] Is this idomatic/good rust code?

Hello people of Rust!

I've got quite some experience with high-level languages like javascript, ruby and python. But I figured it's time to learn something more low level. And given all the good stuff I heard about it, I decided to give Rust a chance!

And boy, even after reading all of the guide and doing some of the excercises here, it's still quite a challenge to wrap your head around all the ownership concepts once you start writing some actual code.

I figured I'd implement a basic EventEmitter to get my feet wet. I had a nice API in mind and then I went ahead to write code for it.It yook me quite some time (2h?) to make it work, but in the end I managed to get it to compile! :confetti_ball:
Here's the link to the code on playground

Now I'm wondering whether this is 1) idomatic rust code and 2) if there would have been any shortcuts to make it more simple (while sticking to the api used in the main function).

Any pointers will be greatly appreciated! :blush:

Thanks a lot,


You was boxing an argument. This is not very efficient, because this could mean that much data is moved, so I changed add_listener to accept Box<Fn(&T)>

Note: I kept original code in comments so you can see the difference quickly.


Instead of add_listener returning a function it could employ RAII.
Return a new structure that implements Drop.

1 Like

RAII is something I've never worked with. So I figured to give them a try!

Here's the result: Rust Playground

Quite a different API, but I believe it's really a lot nicer to automatically unsubscribe as soon as the listener gets out of scope. Not sure whether there's a way around all the Rcs though.


So the RAII could be done right when you returning from add_listener instead of passing it in. You can continue pass the call back into the listener and return the RAII object. See this: Rust Playground I also used the unstable feature impl trait, which allows you to work with anonymous types. See if this something that you can use.

Hello. I'm new to Rust. I'm reading the Rust Programming Language (I bought two copies :grin:) and Programming Rust and as I complete a chapter I go to codewars.com to exercise what I've learned thus far. So there is a lot of guess work and looking things up on doc.rust-lang.org so I don't yet have any real sense of what idiomatic Rust is. Would it be okay to post my codewars solutions here and inquire about if it's idiomatic?

It will be OK if you create a new topic within the "code review" category - this category was created for exactly this kind of discussions.


If it's functional code and you just want advice on how to write it in a more idiomatic way put it in the 'code-review' section. If you need help fixing something don't hesitate to post in the 'help' section. It's best if you mention what solutions you have tried and explain in detail what you did.