3 ![Minimum Rust version: 1.20](https://img.shields.io/badge/Minimum%20Rust%20Version-1.20-brightgreen.svg)
5 You can define traits, structs, and enums that have “associated functions”:
12 println!("foo is an associated function of Struct");
21 These are called “associated functions” because they are functions that are
22 associated with the type, that is, they’re attached to the type itself, and
23 not any particular instance.
25 Rust 1.20 adds the ability to define “associated constants” as well:
35 println!("the ID of Struct is: {}", Struct::ID);
39 That is, the constant `ID` is associated with `Struct`. Like functions,
40 associated constants work with traits and enums as well.
42 Traits have an extra ability with associated constants that gives them some
43 extra power. With a trait, you can use an associated constant in the same way
44 you’d use an associated type: by declaring it, but not giving it a value. The
45 implementor of the trait then declares its value upon implementation:
54 impl Trait for Struct {
59 println!("{}", Struct::ID);
63 Before this feature, if you wanted to make a trait that represented floating
64 point numbers, you’d have to write this:
69 fn infinity() -> Self;
74 This is slightly unwieldy, but more importantly, because they’re functions,
75 they cannot be used in constant expressions, even though they only return a
76 constant. Because of this, a design for `Float` would also have to include
81 const NAN: f32 = 0.0f32 / 0.0f32;
82 const INFINITY: f32 = 1.0f32 / 0.0f32;
88 fn infinity() -> Self {
95 Associated constants let you do this in a much cleaner way. This trait
101 const INFINITY: Self;
106 Leads to this implementation:
111 const NAN: f32 = 0.0f32 / 0.0f32;
112 const INFINITY: f32 = 1.0f32 / 0.0f32;
117 much cleaner, and more versatile.