Associated functions
An associated function lives on a type but has no self receiver. Session::new and String::from are the usual examples; they replace constructors and static methods.
Detailed Explanation
Inside impl Session, a function that does not take self, &self, or &mut self is an associated function. You call it as Session::new(token, user_id). There is no new keyword and no constructor syntax. The convention is that new is the primary constructor, from_* converts from a specific input, and with_* is a constructor with an extra option. None of these names are special to the compiler. Default::default is the trait-shaped constructor.
Associated functions are how you write what Java calls static methods. They do not have a hidden this. They cannot access instance fields because there is no instance until they create one. They are the right place for Session::empty(), for parse functions that return Result<Self, _>, and for constants that need a small amount of code to build.
Methods — functions with a receiver — are associated functions too in the strict sense, and Session::expire(&mut session) is a valid call. Everyday language reserves "associated function" for the no-receiver case, and "method" for the receiver case. The compiler error messages say "associated function" for both.
You can also put associated functions on traits. From::from, Iterator::next (a method), and Default::default are the standard library's vocabulary. A trait associated function without a receiver is called as T::from(value) or <T as From<U>>::from(value) when inference needs the UFCS form. Inherent associated functions shadow trait ones of the same name at the Type:: call site; UFCS picks the trait explicitly.
Why not a constructor keyword: Rust types can have many ways to be built, some fallible, some cheap, some that allocate. A single magic constructor would lie about that. new returning Self is infallible by convention. try_new or from_str returning Result is the fallible pair.
When you write one: any time the type should be named at the call site and there is no existing value to call a method on. When the operation needs a value, write a method. When several types should share a constructor shape, put it on a trait (From, TryFrom, Default).
Code Examples
struct Session {
user_id: u64,
}
impl Session {
fn new(user_id: u64) -> Self {
Self { user_id }
}
fn guest() -> Self {
Self::new(0)
}
}
fn main() {
let guest = Session::guest();
println!("{}", guest.user_id); // prints: 0
}Common Gotchas
`new` is a convention, not a keyword
The compiler will not call it for you. There is no automatic default construction of structs.
Fallible construction should not be named `new`
Return `Result<Self, E>` from `try_new` or `from_*`. Callers expect `new` to be infallible.
UFCS disambiguates
`<Session as From<Raw>>::from(raw)` picks the trait function when an inherent `from` also exists.
No receiver means no instance fields
An associated function cannot read `self.user_id`. It can only use its parameters and other associated items.