Hello, I'm a rust beginner and this is my first post here.
When implementing recursive types in rust is it better to use enum like the cons list example in the book or a struct with Option, something like this?
I'm not going to use this code in any bigger project, it is only for learning purposes. So I'd appreciate both an answer for this specific case and general considerations when making this decision.
In this case, it doesn’t matter much. The enum example is pretty close the classic definition of a cons list from lisp, but your struct construction is perfectly servicable. The difference between the two approaches is primarily about how you expect the example to grow over time:
Use an enum if your object represents one of several distinct possibilities.
Use a struct if you have several consitiuent parts that can vary in a mostly-independent way.
Depending on the complexity of your application, you may end up combining these: it’s common to store a structure inside and enum variant, and also to store an anum as a struct field.
Doesn't the existing machinery of Options in the standard library (the map, map_or and such methods) make it easier to work with the struct approach? I suppose the same methods could be written for the custom enum too, but why reinvent the wheel.
Obligatory: Read Learning Rust With Entirely Too Many Linked Lists. The first few chapters, anyway. I feel your specific questions are already well addressed in the book, and probably a bunch of other questions you don't yet know you have.
Yes, found that website linked in some other thread after I asked this question.
I'm trying to implement binary tree in a similar way (but starting with a struct definition on leetcode) and have run into problems with iteration. But I suppose those are questions for a different post.