Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Rust syntactically separate the data definition of a type from function and method implementations? [closed]

Tags:

syntax

types

rust

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 ?

like image 883
Tiino Avatar asked Oct 21 '25 00:10

Tiino


1 Answers

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:

  • Is there a way other than traits to add methods to a type I don't own?
like image 173
Shepmaster Avatar answered Oct 22 '25 19:10

Shepmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!