Skip to main content
Version: dev

StructDefinition

std::meta::struct_def contains methods on the built-in StructDefinition type. This type corresponds to struct Name { field1: Type1, ... } items in the source program.

Methods

add_attribute

add_attribute
fn add_attribute<let N: u32>(self, attribute: str<N>) {}

Source code: noir_stdlib/src/meta/struct_def.nr#L3-L5

Adds an attribute to the struct.

as_type

as_type
fn as_type(self) -> Type {}

Source code: noir_stdlib/src/meta/struct_def.nr#L10-L12

Returns this struct as a type in the source program. If this struct has any generics, the generics are also included as-is.

generics

generics
fn generics(self) -> [Type] {}

Source code: noir_stdlib/src/meta/struct_def.nr#L21-L23

Returns each generic on this struct.

Example:

#[example]
struct Foo<T, U> {
bar: [T; 2],
baz: Baz<U, U>,
}

comptime fn example(foo: StructDefinition) {
assert_eq(foo.generics().len(), 2);

// Fails because `T` isn't in scope
// let t = quote { T }.as_type();
// assert_eq(foo.generics()[0], t);
}

fields

fields
fn fields(self) -> [(Quoted, Type)] {}

Source code: noir_stdlib/src/meta/struct_def.nr#L28-L30

Returns each field of this struct as a pair of (field name, field type).

has_named_attribute

has_named_attribute
fn has_named_attribute(self, name: Quoted) -> bool {}

Source code: noir_stdlib/src/meta/struct_def.nr#L15-L17

Returns true if this struct has a custom attribute with the given name.

module

module
fn module(self) -> Module {}

Source code: noir_stdlib/src/meta/struct_def.nr#L33-L35

Returns the module where the struct is defined.

name

name
fn name(self) -> Quoted {}

Source code: noir_stdlib/src/meta/struct_def.nr#L38-L40

Returns the name of this struct

Note that the returned quoted value will be just the struct name, it will not be the full path to the struct, nor will it include any generics.

set_fields

set_fields
fn set_fields(self, new_fields: [(Quoted, Type)]) {}

Source code: noir_stdlib/src/meta/struct_def.nr#L47-L49

Sets the fields of this struct to the given fields list where each element is a pair of the field's name and the field's type. Expects each field name to be a single identifier. Note that this will override any previous fields on this struct. If those should be preserved, use .fields() to retrieve the current fields on the struct type and append the new fields from there.

Example:

// Change this struct to:
// struct Foo {
// a: u32,
// b: i8,
// }
#[mangle_fields]
struct Foo { x: Field }

comptime fn mangle_fields(s: StructDefinition) {
s.set_fields(&[
(quote { a }, quote { u32 }.as_type()),
(quote { b }, quote { i8 }.as_type()),
]);
}