Hacker News new | past | comments | ask | show | jobs | submit login

I've noticed this and while I don't use it much it has caught me off guard once or twice. And while it wasn't the end of the world, I wasn't too fond of the solutions I came up with. Is there a reason why they can't have fields? Why wouldn't they just be an "extension" to a struct/enum, modifying their memory representation?



Rust doesn't do single inheritance, basically.

If they had fields, what would you do when you implemented two of them on a struct? It also muddles up the ability to tack on traits in later crates.

Traits aren't supposed to be used the way you do single inheritance. Rust prefers composition over inheritance, so you combine structs and enums to get what you want there.


> Is there a reason why they can't have fields?

The design isn't done yet: https://github.com/rust-lang/rfcs/pull/1546


Note that this is different from what's being asked, what's being asked is why they can't have fields like abstract classes that get appended to the original struct. That would make traits more like mixins.

That RFC lets you declare fields that the trait implementor is supposed to provide; implementing a trait will not automatically add a field, instead, you will be forced to add such a field yourself (unless one already exists) and link it to the trait field.

It's a more rusty way of addressing many of the same use cases, but it's not the same thing. It's basically sugar for declaring a getter and setter as trait/interface methods.


While it's not what I asked, I actually like the answer as long as I can provide overrideable default methods in the that use the lvalues. I can't think of any of my own use cases that couldn't adequately be covered by it.


Ah yeah, I read your post wrong, my bad!


Oh, yeah, like I said it solves many of the same use cases, it's just not the same thing :)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: