1.5 KiB
Hints
General
1. Implement the new()
method
-
The
new()
method receives the arguments we want to instantiate aUser
instance with. It should return an instance ofUser
with 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
name
method returns a&str
when thename
field on theUser
struct is aString
. How can we get&str
andString
to play nice with each other? -
There's no need to use a
return
statement 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.