Object-oriented languages like C++ and Java use objects to define behaviour for specific data. Because their meanings are closely related, they are declared in the same context: the class.
Rust chose to separate them syntactically.
C++ style:
class Foo {
public:
int get_bar();
private:
int _bar;
}
Rust style:
struct Foo {
bar: i8,
}
impl Foo {
pub fn bar() -> i8 {
bar
}
}
Isn't Rust an Object Oriented language ?
In languages like C++ or Java, the set of methods that a type implements is fixed when the type is defined. That means that a single syntactical construct is sufficient to express the two related concepts.
In Rust, you can implement a trait for a type without the original implementing code ever knowing about it. This requires that there be syntax for implementing the trait separately from the data definition. Once that requirement is present, it's less confusing to use the same syntax universally, even within a single file.
Crate 1:
struct Foo;
Crate 2:
trait Price {
fn price(&self) -> u8;
}
impl Price for crate1::Foo {
fn price(&self) -> u8 {
42
}
}
Additionally, implementing multiple traits for the same type may result in name collisions of the methods. Separating out each trait's implementation into a separate syntax block clearly disambiguates which methods are being implemented.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With