1.5 KiB
Hints
General
1. Implement the new() method
-
The
new()method receives the arguments we want to instantiate aUserinstance with. It should return an instance ofUserwith the specified name, age, and weight. -
See here for additional examples on defining and instantiating structs.
2. Implement the getter methods
-
The
name(),age(), andweight()methods are getters. In other words, they are responsible for returning the corresponding field from a struct instance. -
Notice that the
namemethod returns a&strwhen thenamefield on theUserstruct is aString. How can we get&strandStringto play nice with each other? -
There's no need to use a
returnstatement in Rust unless you expressly want a function or method to return early. Otherwise, it's more idiomatic to utilize an implicit return by omitting the semicolon for the result we want a function or method to return. It's not wrong to use an explicit return, but it's cleaner to take advantage of implicit returns where possible.
fn foo() -> i32 {
1
}
- See here for some more examples of defining methods on structs.
3. Implement the setter methods
-
The
set_age()andset_weight()methods are setters, responsible for updating the corresponding field on a struct instance with the input argument. -
As the signatures of these methods specify, the setter methods shouldn't return anything.