A static method is a function available through a type rather than through an instance of that type. In Rust, this is commonly written with the type name followed by ::, as in Complex::new(...). The new() name is a convention used by many types, not a feature required by the language. section 2.3.4
Static methods are useful when:
- A type provides a convenient way to construct a value, often applying defaults or reducing initialization clutter. section 2.3.4
- A struct acts as a namespace for related operations without storing state. Clock::get() reads the local system clock, while Clock::set() is reserved for later implementation. section 9.6.1
- The operation belongs to the type itself rather than to a particular value, so no instance is required before calling it. section 2.3.4
Constructing a complex number
use num::complex::Complex; fn main() { let a = Complex { re: 2.1, im: -1.2 }; let b = Complex::new(11.1, 22.2); let result = a + b; println!("{} + {}i", result.re, result.im); } The literal form assigns fields directly. Complex::new(11.1, 22.2) calls a static method supplied by the type. Both values can then participate in the calculation. section 2.3.4
Listing 9.3 Reading the time from the local system clock
2 use chrono::{DateTime};
3 use chrono::{Local};
4
5 struct Clock;
6
7 impl Clock {
8 fn get() -> DateTime<Local> { #1
9 Local::now()
10 }
11
12 fn set() -> ! {
13 unimplemented!()
14 }
15 }
Inspect a zero-field Clock struct whose associated functions expose time operations through the type name. section 9.6.1




