noir
noir copied to clipboard
Cannot access trait type methods from built-in types.
Aim
Define a trait for all numeric types:
trait FromField {
fn from_field(x: Field) -> Self;
}
impl FromField for u8 {
fn from_field(x: Field) -> Self {
x as u8
}
}
fn main(x: Field) {
u8::from_field(x);
}
Expected Behavior
It should compile
Bug
Compiler errors out:
error: Unexpected u8, expected one of for, }, expression, statement ┌─ /mnt/user-data/grego/repos/noir-experiments/traits_on_u/src/main.nr:12:5 │ 12 │ u8::from_field(x); │ -- │
To Reproduce
Try to compile the provided example
Project Impact
Nice-to-have
Impact Context
No response
Workaround
None
Workaround Description
No response
Additional Context
No response
Installation Method
Binary (noirup
default)
Nargo Version
No response
NoirJS Version
No response
Would you like to submit a PR for this Issue?
None
Support Needs
No response
This is because u8
is a keyword where the Foo::method
syntax currently expects an identifier for Foo
.
If anyone reading is encountering this issue, the workaround is to use the static trait method syntax FromField::from_field(x)
. If type annotations are needed, you can add a let binding:
let y: u8 = FromField::from_field(x);