Hacker News new | ask | show | jobs
by ww520 3400 days ago
Struct is for data and Struct's implementation is for methods. Trait is like interface, just a set of function signatures.
1 comments

Why isn't it called interface then?
Because they are traits [1], not interfaces, and they also have some features from type classes [2].

When you create a class in an OOP language, you have do declare all interfaces it supports, and provide implementations for them (or mark the class as abstract). In Rust's case, you declare the data separately as a struct declaration, and then implement the traits you want in impl declarations. You can also implement traits for other traits, or for types from other modules, including the standard library.

Finally, compared to traditional OOP interfaces Rust's traits can require static functions in addition to instance methods and they can also implement methods with an overridable default implementation.

[1] https://en.wikipedia.org/wiki/Trait_(computer_programming) [2] https://en.wikipedia.org/wiki/Type_class

Ah, I read the Wiki article and my impression of traits was "interfaces with implementation" and as far as I could tell, Rust traits have no implementation, they 'need' impl(emendations) so they seemed more like interferences to me :)
You can have default implementations for methods if you'd like.