[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.


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

Here’s the result: https://is.gd/jlH7Hx

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: https://play.rust-lang.org/?gist=fee8db781d4cab559354445e94ba05ee&version=nightly I also used the unstable feature impl trait, which allows you to work with anonymous types. See if this something that you can use.