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!
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).
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.
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 ) 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?
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.