Enum or struct with Option for recursive types?

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?

struct Cons {
    val: i32,
    next: Option<Box<Cons>>,

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.

1 Like

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.

1 Like

I think you're right. I flipped around my cons list when I started learning, and found the Option approach superior. I'm still learning though.

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.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.