Struct show_notes::e004::struct_container::MethodDemonstrator
source · pub struct MethodDemonstrator {
pub an_int: i64,
pub a_string: String,
a_tuple: (f64, String),
}
Expand description
Shows how methods work. Elaborates only a little on the e001 examples.
Fields§
§an_int: i64
§a_string: String
§a_tuple: (f64, String)
A tuple holding a floating point value and a string slice. (We’ll discuss string slices in a future episode.)
Implementations§
source§impl MethodDemonstrator
impl MethodDemonstrator
sourcepub fn new() -> MethodDemonstrator
pub fn new() -> MethodDemonstrator
A standard constructor pattern.
You’ve seen this before, in the e001 code!
Note that Rust doesn’t have constructors in the same sense as C++
or Java: you can construct a MethodDemonstrator
just as this
function does somewhere else. Using new
is a convenient
convention, so you can just call MethodDemonstrator::new()
to get
an instance, rather than needing to worry about the details of the
struct.
This is particularly important because not all types are
necessarily public; you may not be able to construct a given
struct
correctly if it has hidden types, especially computed
properties, which should be initialized during its construction.
sourcepub fn method(&self)
pub fn method(&self)
A standard struct instance method.
Note that instance methods take a reference to self
as the
first argument. It needs to be a reference for normal methods,
because if it isn’t, the struct instance will be moved into the
function—the method will own, not just borrow—the reference,
and after the method call ends, the item will be destroyed.
Of course, if you need to write a custom destructor for a more complex type, you now have a pretty good idea how to write the first argument to that method…
A getter for data which is not publicly accessible in the type.
If you try to access the tuple contents directly, e.g. with an
instance of the struct outside this module, you will fail. (See
the example in demonstrate_methods
.)
The data can be accessed by the struct itself, however, so you can get or set the data, as here.
We use clone
because we need to get not the items themselves
(which we could otherwise only get as references) but their values;
the clone
method is from the Clone
trait, which is available on
many basic types in the system. Again, we will return to trait
s in
a later episode.