Associated functions
- Rust course
- Beginner
- Lesson 74/115
- 4 min
Build constructors with associated functions that take no self.
Associated functions
Functions that don't take self can also be written inside impl; these are associated functions, not methods, and are called with Type::name(). The most common is the constructor; in Rust new isn't a keyword, just a convention:
impl Kutu {
fn new(en: u32, boy: u32) -> Self {
Self { en, boy }
}
fn kare(n: u32) -> Self {
Self { en: n, boy: n }
}
}
let k = Kutu::kare(5);Self and constants
Self is an alias for the type of the impl block; even if the type name changes, the code doesn't. Associated constants can be defined inside impl too:
impl Kutu {
const BIRIM: Kutu = Kutu { en: 1, boy: 1 };
}
println!("{}", Kutu::BIRIM.en); // 1A constructor can also validate: fn new(en: u32, boy: u32) -> Option<Self> can return None for a zero size.
Practice Constructors
Write fn new(en: u32, boy: u32) -> Self, fn kare(n: u32) -> Self and fn alan(&self) -> u32 inside impl Kutu. Print the results of Kutu::kare(5).alan() and Kutu::new(2, 3).alan().
Starter code
struct Kutu {
en: u32,
boy: u32,
}
fn main() {
// buraya yaz
}Sample solution
struct Kutu {
en: u32,
boy: u32,
}
impl Kutu {
fn new(en: u32, boy: u32) -> Self {
Self { en, boy }
}
fn kare(n: u32) -> Self {
Self { en: n, boy: n }
}
fn alan(&self) -> u32 {
self.en * self.boy
}
}
fn main() {
println!("{} {}", Kutu::kare(5).alan(), Kutu::new(2, 3).alan());
}Expected output
25 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is <code>String::from("a")</code>?
- A field access
- An associated function call Correct answer
- A method call
- A macro
Explanation: Every function called with :: that doesn't take self is an associated function; String::new and Vec::with_capacity are too.
2 Call the constructor
let k = Kutu____new(2, 3);
let k = Kutu::new(2, 3);
Explanation: Associated functions are called with the type name and ::.
3 Syntax and kind
| Term | Meaning |
|---|---|
Kutu::new(2, 3) |
Associated function |
k.alan() |
Method |
Kutu::BIRIM |
Associated constant |
-> Self |
Returns the type itself |