rustinterfacetraits

Is Rust trait the same as Java interface


It looks to me that Rust's trait is the same thing as Java's interface - a set of functions that needs to be implemented on object.

Is there a technical reason for naming it trait not interface or is it just some preference?


Solution

  • Rust traits and Java interfaces both address the problem of having multiple possible implementations that adhere to some convention/protocol/interface for interacting with a value/object, without constraining the implementation details as a Java superclass does. They can be used in many of the same situations. However, they are different in many details, mostly meaning that Rust traits are more powerful:

    There's probably many more details that could be mentioned, but I think these cover a lot of the ways in which you can or must use them differently even though they are meant for the same tasks.


    As to the name “trait” versus “interface”, this is due to an existing concept of traits in computer science which are considered to have several specific properties, mostly that there is no inheritance and no overriding involved in implementing and using traits. This is closely related to the “separate namespace” I mentioned above.