nrc/r4cppp

Methods on structs

Opened this issue · 0 comments

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.