O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Struct methods

It's often the case that you wish to write functions that operate on a specific struct or return the values of a specific struct. That's when you write implementation blocks with the impl keyword.

For instance, we could extend the previously defined character struct with two methods: a constructor that takes a name and sets default values for all the character attributes and a getter method for character strength:

// structmethods.rs struct Character {   strength: u8,   dexterity: u8,   constitution: u8,   wisdom: u8,   intelligence: u8,   charisma: u8,   name: String, } impl Character {   fn new_named(name: String) -> Character {     Character {        strength: 9,       constitution: 9,       dexterity: 9,      wisdom: 9,       intelligence: 9,  charisma: 9, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required