5
votes

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.

1
This lets you provide implementations for user-defined traits for types that you didn't define. That means the set of "methods" on a struct can grow even outside the file in which the struct is defined.Alec

1 Answers

11
votes

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.