Attributes
Attributes attach metadata or behavior to declarations.
Struct tags
Section titled “Struct tags”#[json]
Section titled “#[json]”Add #[json] to a struct to generate Go JSON struct tags for all fields:
#[json]struct User { name: string, age: int, active: bool,}Generated Go:
type User struct { Name string `json:"name"` Age int `json:"age"` Active bool `json:"active"`}Serialization attributes accept options:
#[json]struct Config { #[json(omitempty)] timeout: Option<int>,omitted if None
#[json(skip)] internal_id: int,never serialized
#[json(string)] large_number: int64,encoded as "1234", not 1234}| Option | Effect |
|---|---|
omitempty | Omit field if empty |
!omitempty | Include field if empty |
omitzero | Omit field if it holds a zero value |
!omitzero | Include field if it holds a zero value |
skip | Exclude field |
snake_case | Convert field name to snake_case |
camel_case | Convert field name to camelCase |
string | Encode numbers as strings |
Struct-level options apply to all fields. A field-level option overrides them, and an explicit name overrides both:
#[json(camel_case)]struct UserProfile { user_name: string,"userName" from camel_case
created_at: int,"createdAt" from camel_case
#[json("userID")] id: int,"userID", camel_case overridden}omitempty does not omit a struct, enum, tuple, or non-empty Array<T, N> field, because Go never treats these as empty. Use omitzero for these fields.
Other serializers
Section titled “Other serializers”More supported attributes:
#[xml]#[yaml]#[toml]#[db]#[bson]#[mapstructure]#[msgpack]Attributes stack:
#[json]#[db]struct User { #[json("userName")] #[db("user_name")] name: string,}#[tag]
Section titled “#[tag]”For custom tags, use #[tag]:
#[json]struct Input { #[tag("validate", "required")] email: string,}Generated Go:
type Input struct { Email string `json:"email" validate:"required"`}For more complex tags, use a backticked string:
#[json]struct Account { #[tag(`validate:"required,email" gorm:"unique"`)] email: string,}Generated Go:
type Account struct { Email string `json:"email" validate:"required,email" gorm:"unique"`}Generated code
Section titled “Generated code”#[iterate]
Section titled “#[iterate]”#[iterate] gives an enum an associated function variants(), which returns a Slice of all variants in declaration order:
#[display]#[iterate]enum Direction { North, East, West, South,}
for direction in Direction.variants() { fmt.Println(direction)prints North, East, West, South}#[iterate] works only on enums whose variants carry no data.
#[display]
Section titled “#[display]”By default a struct or enum has no display form. Printing one falls back to Go’s %v, and interpolating one in an f-string is rejected.
struct Point { x: int, y: int,}
fn log_position(p: Point) { fmt.Println(p)prints {1 2}}Add #[display] to render it as a readable string instead.
#[display]struct Point { x: int, y: int,}
fn log_position(p: Point) { fmt.Println(p)prints Point { x: 1, y: 2 }}#[display] also gives the enum or struct a to_string() method.
fn label(p: Point) -> string { p.to_string()"Point { x: 1, y: 2 }"}#[equality]
Section titled “#[equality]”== and != work only on Comparable types:
- primitives
- structs, enums, tuples, and arrays whose components are all
Comparable
struct User { name: string,Comparable age: int,Comparable}let u1 = User { name: "Alice", age: 30 }let u2 = User { name: "Alice", age: 30 }
u1 == u2trueMaps and slices are not Comparable. Instead, they have a built-in equals() method, which compares structurally:
- slices are compared element by element
- maps are compared by keys and values
let s1 = [1, 2, 3]let s2 = [1, 2, 3]
s1.equals(s2)trueA struct with a field that is not Comparable is not Comparable either:
struct Order { id: int,Comparable tags: Slice<string>,not Comparable}let o1 = Order { id: 1, tags: ["a"] }let o2 = Order { id: 1, tags: ["a"] }
o1 == o2error: Order cannot be compared with ==To compare a struct or enum that is not Comparable, mark it with #[equality]. This attribute generates an equals() method that compares structurally, like the built-in one on maps and slices.
#[equality]struct Order { id: int, tags: Slice<string>,}let o1 = Order { id: 1, tags: ["a"] }let o2 = Order { id: 1, tags: ["a"] }
o1.equals(o2)trueThe generated equals() method compares each field by these rules:
==for fields that support==equals()for slice and map fields- the field type’s own
equals()for nested#[equality]types
If you need a custom comparator, write an equals method yourself:
struct Fraction { numerator: int, denominator: int,}
impl Fraction { fn equals(self, other: Fraction) -> bool { self.numerator * other.denominator == other.numerator * self.denominator }}let f1 = Fraction { numerator: 1, denominator: 2 }let f2 = Fraction { numerator: 2, denominator: 4 }
f1.equals(f2)true#[equality] works on generic structs and enums, as long as the type parameter is bound by Comparable, Ordered, or an interface that declares equals().
#[equality]struct Cart<T: Comparable> { items: Slice<T>}let c1 = Cart { items: [1, 2, 3] }let c2 = Cart { items: [1, 2, 3] }
c1.equals(c2)true#[default]
Section titled “#[default]”Out of the box, an enum has no zero value.
enum Status { Active, Paused, Stopped,}
let queue = Slice.make<Status>(2)error: Status has no zero valuelet slots = Array.new<Status, 3>()error: Status has no zero valuePlace #[default] on an enum variant to make it the zero value.
enum Status { Active, Paused, #[default] Stopped,}
let queue = Slice.make<Status>(2)[Stopped, Stopped]let slots = Array.new<Status, 3>()[Stopped, Stopped, Stopped]An enum’s default appears wherever a zero value is expected.
struct Job { pub name: string, pub status: Status,}
let job = Job { name: "build", .. }job.status is Status.Stopped
let by_name = Map.new<string, Status>()let missing = by_name["absent"]Status.Stopped
let initial = zero<Status>()Status.Stopped#[allow]
Section titled “#[allow]”#[allow(lint)] silences a lint. Where to place it depends on the lint. To silence several lints, list them: #[allow(unused_struct_field, unused_type)].
For most lints, place the attribute on the function whose code is flagged:
#[allow(match_on_bool)]silences the lint for this functionfn describe(ready: bool) -> string { match ready { true => "go", false => "wait", }}For unused-value lints (unused_result, unused_option, unused_partial, unused_value), place #[allow] on the function whose result is ignored, so every call to it stops warning. An #[allow] on the calling function has no effect.
import "go:os"
#[allow(unused_result)]silences the lint at every call belowfn warm_cache(path: string) -> Result<Slice<byte>, error> { os.ReadFile(path)}
fn main() { warm_cache("/config") warm_cache("/data")}For the unused-item lints (unused_function, unused_type, unused_struct_field, unused_enum_variant), place #[allow] on the flagged declaration itself. An allow on a struct or enum also covers its fields and variants.
#[allow(unused_enum_variant)]enum Direction { North, South,silences the lint for South}
fn main() { let _ = Direction.North}