From 263922da5af9a8d7bf85cbe268f381dc1f650913 Mon Sep 17 00:00:00 2001 From: Savio <72797635+Savio-Sou@users.noreply.github.com> Date: Fri, 21 Feb 2025 02:15:20 +0900 Subject: [PATCH] chore: Copy #7387 docs into v1.0.0-beta.2 versioned_docs (#7458) --- .../noir/concepts/traits.md | 56 ++++++++++++++----- 1 file changed, 42 insertions(+), 14 deletions(-) diff --git a/docs/versioned_docs/version-v1.0.0-beta.2/noir/concepts/traits.md b/docs/versioned_docs/version-v1.0.0-beta.2/noir/concepts/traits.md index 13818ecffac..17cc04a9751 100644 --- a/docs/versioned_docs/version-v1.0.0-beta.2/noir/concepts/traits.md +++ b/docs/versioned_docs/version-v1.0.0-beta.2/noir/concepts/traits.md @@ -111,6 +111,48 @@ fn foo(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: @@ -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.