Caution

You’re reading a draft of the Ferrocene Language Specification. Some parts of this document might be missing, incomplete or incorrect. Our aim is to have the specification ready by the end of 2022.

10. Associated Items

Syntax

AssociatedItem ::=
    OuterAttributeOrDoc* (AssociatedItemWithVisibility | TerminatedMacroInvocation)

AssociatedItemWithVisibility ::=
    VisibilityModifier? (
        ConstantDeclaration
      | FunctionDeclaration
      | TypeAliasDeclaration
    )

Legality Rules

10:1 An associated item is an item that appears within an implementation or a trait.

10:2 An associated constant is a constant that appears as an associated item.

10:3 An associated function is a function that appears as an associated item.

10:4 An associated type is a type alias that appears as an associated item.

10:5 An associated type shall not be used in the path-in-expression of a struct expression.

10:6 An associated type with a TypeBoundList shall appear only as an associated trait type.

10:7 An associated implementation constant is an associated constant that appears within an implementation.

10:8 An associated implementation constant shall have a constant initializer.

10:9 An associated implementation function is an associated function that appears within an implementation.

10:10 An associated implementation function shall have a function body.

10:11 An associated implementation type is an associated type that appears within an implementation.

10:12 An associated implementation type shall have an initialization type.

10:13 An associated trait constant is an associated constant that appears within a trait.

10:14 An associated trait function is an associated function that appears within a trait.

10:15 An associated trait type is an associated type that appears within a trait.

10:16 An associated trait type shall not have an initialization type.

10:17 An associated trait type has an implicit core::marker::Sized bound.

10:18 An associated trait type of the form

trait T {
    type X: Bound;
}

10:19 is equivalent to a where clause of the following form:

trait T where Self::X: Bound {
    type X;
}

10:20 A method is an associated function with a receiver.

Examples

trait Greeter {
    const MAX_GREETINGS: i32;

    fn greet(self, message: &str);
}

struct Implementor {
    delivered_greetings: i32
}

impl Greeter for Implementor {
    const MAX_GREETINGS: i32 = 42;

    fn greet(mut self, message: &str) {
        if self.delivered_greetings < Self::MAX_GREETINGS {
            self.delivered_greetings += 1;
            println!("{}", message);
        }
    }
}