Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Methods on structs #79

Open
RGates94 opened this issue Apr 24, 2019 · 0 comments
Open

Methods on structs #79

RGates94 opened this issue Apr 24, 2019 · 0 comments

Comments

@RGates94
Copy link

In the section on data types it states:

A rust struct is similar to a C struct or a C++ struct without methods. Simply a list of named fields. The syntax is best seen with an example:

This statement is misleading because it suggests that methods can not be defined for a struct, while methods can be defined via impl blocks. There is a brief mention of this possibility with:

Behaviour is defined by functions and those can be defined in traits and impls

However, this suggests the impls would define functions rather than methods, while in fact impls can define both.

For reference here is a short example outlining the type of functionality I am describing.

struct Example {
    foo: i16,
    bar: i16,
}

impl Example {
    fn baz(&self) -> i16 {
        self.foo + self.bar
    }
}

fn main() {
    let ex = Example {
        foo: 3,
        bar: -1,
    };
    println!("{}", ex.baz());
}

This will print 2. I believe a section on this functionality should be added as it is critical to creating useful abstractions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant