liveBook · Manning

Static method

As explained in Rust in Action: Systems programming concepts and techniques

A static method is a function associated with a type rather than with an instance of that type.

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

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Explains the type-versus-instance distinction and demonstrates construction and namespacing, but stops short of language-level method internals.
Examples
Demonstrates Complex::new() for complex numbers and Clock::get() for reading local system time.
What it assumes
Assumes basic Rust types, structs, fields, functions, and method-call syntax while teaching the type-versus-instance distinction directly.
What you can do after
Apply it via Rust type syntax to construct values and expose operations without first creating an instance.
How it connects
Connects types, instances, structs, fields, methods, constructors, namespaces, and traits.

Also explained in

Compare how 5 books explain static method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.