rust / intermediate
Snippet
Struct Methods and Associated Functions with impl
The 'impl' block defines methods and associated functions for structs. Associated functions like 'from_celsius' and 'from_fahrenheit' don't take 'self' and serve as constructors, using 'Self' as a shorthand for the struct type. Method functions take '&self' (or '&mut self') to operate on instance data. This encapsulation follows Rust's object-oriented principles while maintaining safety and ownership semantics.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
struct Temperature {celsius: f64,}impl Temperature {fn from_celsius(celsius: f64) -> Self {Self { celsius }}fn from_fahrenheit(fahrenheit: f64) -> Self {Self {celsius: (fahrenheit - 32.0) * 5.0 / 9.0,}}fn to_fahrenheit(&self) -> f64 {self.celsius * 9.0 / 5.0 + 32.0}fn to_kelvin(&self) -> f64 {self.celsius + 273.15}fn format(&self) -> String {format!("{:.2}°C = {:.2}°F = {:.2}K",self.celsius,self.to_fahrenheit(),self.to_kelvin())}}fn main() {let t1 = Temperature::from_celsius(25.0);let t2 = Temperature::from_fahrenheit(98.6);println!("{}", t1.format());println!("{}", t2.format());}
Breakdown
1
struct Temperature { celsius: f64 }
Struct with single field storing temperature in Celsius
2
impl Temperature { ... }
Implementation block for Temperature struct
3
fn from_celsius(celsius: f64) -> Self { Self { celsius } }
Associated constructor function returning new Self instance
4
fn to_fahrenheit(&self) -> f64
Method taking immutable reference, computes Fahrenheit conversion
5
self.to_fahrenheit()
Calling another method on the same instance
6
Self { celsius }
Self shorthand syntax, equivalent to Temperature { celsius }