Skip to content

Commit

Permalink
chore: document traits required to be in scope (#7387)
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite authored Feb 14, 2025
1 parent e73f8cd commit 2391a8e
Showing 1 changed file with 42 additions and 14 deletions.
56 changes: 42 additions & 14 deletions docs/docs/noir/concepts/traits.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,48 @@ fn foo<T, U>(elements: [T], thing: U) where
}
```

## Invoking trait methods

As seen in the previous section, the `area` method was invoked on a type `T` that had a where clause `T: Area`.

To invoke `area` on a type that directly implements the trait `Area`, the trait must be in scope (imported):

```rust
use geometry::Rectangle;

fn main() {
let rectangle = Rectangle { width: 1, height: 2};
let area = rectangle.area(); // Error: the compiler doesn't know which `area` method this is
}
```

The above program errors because there might be multiple traits with an `area` method, all implemented
by `Rectangle`, and it's not clear which one should be used.

To make the above program compile, the trait must be imported:

```rust
use geometry::Rectangle;
use geometry::Area; // Bring the Area trait into scope

fn main() {
let rectangle = Rectangle { width: 1, height: 2};
let area = rectangle.area(); // OK: will use `area` from `geometry::Area`
}
```

An error will also be produced if multiple traits with an `area` method are in scope. If both traits
are needed in a file you can use the fully-qualified path to the trait:

```rust
use geometry::Rectangle;

fn main() {
let rectangle = Rectangle { width: 1, height: 2};
let area = geometry::Area::area(rectangle);
}
```

## Generic Implementations

You can add generics to a trait implementation by adding the generic list after the `impl` keyword:
Expand Down Expand Up @@ -325,20 +367,6 @@ let x: Field = Default::default();
let result = x + Default::default();
```

:::warning

```rust
let _ = Default::default();
```

If type inference cannot select which impl to use because of an ambiguous `Self` type, an impl will be
arbitrarily selected. This occurs most often when the result of a trait function call with no parameters
is unused. To avoid this, when calling a trait function with no `self` or `Self` parameters or return type,
always refer to it via the implementation type's namespace - e.g. `MyType::default()`.
This is set to change to an error in future Noir versions.

:::

## Default Method Implementations

A trait can also have default implementations of its methods by giving a body to the desired functions.
Expand Down

0 comments on commit 2391a8e

Please sign in to comment.