Hello Method Calls!
In Ownership and References, we’ve learned three fundamental concepts in Rust:
-
How to create our own data types using
struct
-
How ownership and moving works
-
How to use references and mutable references
So far, we’ve demonstrated these concepts using functions. We pass ownership of a value from one function to another. Or we borrow a reference and pass that reference into a function.
There’s another concept in Rust that is very close to functions, called methods. We’re going to introduce methods now. We’ll see that they can sometimes be easier to use than functions.
When we learned about functions, we had two sides to the coin:
-
How do you call a function?
-
How do you define or implement a function?
We have the same two sides in Rust. We’ll first demonstrate what a method call looks like using some methods on types you’re already familiar with.
How long is the string "Hello"
? You can count the letters and tell me 5. But programmers are lazy! Why should we do the work when the computer can do it instead? You might imagine that we’d have a length
or len
function. But it turns out we don’t. Instead, we have a len
method:
Get hands-on with 1200+ tech skills courses.