Keyword auto-imported

impl

Source: compiler/src/builtin_docs/keywords.md

Adds methods to a type (impl Type { … }) or implements a trait for it (impl Trait for Type { … }).

Methods have an implicit self; pub makes them callable from outside the type, and static fn declares one that is called on the type. An inherent fn drop() is a finalizer the garbage collector runs once.

A generic type’s inherent impl declares its parameters, impl Cell<T> { … } (bounds as impl Cell<T: Eq>). impl Show<Foo> { … } is an error: a trait instance is always written impl Show for Foo.

class Celsius {
    pub deg: float,
}

trait Describe<T> {
    fn describe(T x) -> string;
}

impl Celsius {
    pub fn to_fahrenheit() -> float {
        return self.deg * 9.0 / 5.0 + 32.0;
    }
}

impl Describe for Celsius {
    fn describe(Celsius c) -> string {
        return "temperature";
    }
}

See also#

  • fn: Declares a function, a method, or (written in an expression) an anonymous function.
  • let: Declares a mutable local variable.
  • const: Declares a binding that cannot be reassigned: a local, a module constant, or a class field that is set only by new.
  • static: Declares a module-level or class-level slot shared by the whole program, or a method without self.
  • readonly: A read-only view of a value: nothing reachable through it can be changed.
  • if: Runs a block when a bool condition is true.
  • else: Introduces the branch of an if that runs when its condition is false (or its pattern does not match).
  • while: Repeats a block while a bool condition is true.
↑ ↓ navigate ↵ open