Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to declare methods outside a struct in Rust?

Why are methods created outside the struct?

In languages like C#, you can add the methods inside the struct. I know that in languages like C and C++ you have header files so it makes sense, but as far as I know I can't create header files in Rust.

like image 645
Jan-Fokke Avatar asked Mar 24 '17 21:03

Jan-Fokke


1 Answers

In most languages, "methods" are just some syntactic sugar. You don't actually have an object and call its methods, you have a function that takes a reference to that object and then does stuff with it. In contrast to regular functions, the reference to the object is passed implicitly by using the dot notation.

struct Foo {
    //...
}

impl Foo {
    fn do_something(self: &Self) {   //"self: &Self" is a more verbose notation for "&self"
        //...
    }
}

So calling it like this

my_foo.do_something();

Is essentially the same as

Foo::do_something(&my_foo);

I think it's a decision made by the Rust developers to make it more clear that a struct is nothing else than just a set of data.

This is also what allows trait implementation for already existing types.

like image 162
Sogomn Avatar answered Oct 06 '22 22:10

Sogomn