Associated functions on structs
Rust makes it possible to call a method in two ways. For example, when we want to obtain the length of a string, you can do:
// see code in Chapter 6/code/paradigm.rs let str1 = "abc"; println!("{}", str::len(str1)); // 3 println!("{}", str1.len()); // 3
The first way is procedural and calls the len
function from the str
crate in the standard library and passes the string slice str1
as a parameter. The second way which is more object-oriented and more commonly used calls the len
method on the string slice str1
. If you look it up in the API docs, you can see it has the signature:
fn len(&self) -> usize
It effectively takes a reference (&
) to self
as a parameter.
So we see that Rust caters also for more object-oriented developers, who are used to the object.method()
type of notation instead of function(object)
type of notation. In Rust, we can define associated functions and methods on a struct
, which pretty much compares to the traditional...