Attributes
An attribute is a name in square brackets that tells the compiler something
about the declaration below it. Each attribute goes on its own line, above
its target, as pep-fmt writes it, except a parameter's, which stay on its
line, in front of it:
# Attributes, each on its own line above what it applies to.
[Target(OS(Windows))]
system_name(): String {
return "Windows";
}
[Target(!OS(Windows))]
system_name(): String {
return "not Windows";
}
[Deprecated("use 'system_name' instead", "system_name")]
os_name(): String {
return system_name();
}
# A parameter's attributes stay on its line, in front of it.
keep([Move] names: Array<String>): ulong {
return names.count;
}
main(): int {
print(system_name().size > 0);
var names = ["a", "b"];
print(keep(move(names)));
return 0;
}
# Output:
# true
# 2
The built-in attributes are each covered in the chapter for what they do:
| Attribute | Goes on | Chapter |
|---|---|---|
[Value] | a struct or enum | Value structs, value enums |
[Equatable] | a struct or enum | Deriving == and hash |
[Implicit] | a constructor | Implicit conversions |
[Alias], [Rename] | a parameter | Other names for a parameter |
[Shared] | a struct | What threads can share |
[ThreadLocal] | a module-scope var | Thread-local variables |
[Isolated] | a struct | What a lock body may do |
[Move], [MoveSource] | a parameter | Handing a reference over with move |
[NotCopyable], [Locked] | a struct; a parameter | the reference |
[Unsafe] | a function | Removing the checks |
[Likely], [Unlikely] | an if or a match arm | Branch hints |
[Cold] | a function | Cold functions |
[Target] | most declarations, and blocks | Platform selection |
[BuildOption] | a declaration or a block | Build options |
[Link] | an extern function | Linking |
[Export] | a function | Calling Pepper from C |
[Test], [ShouldPanic] | a function | Unit tests |
[Deprecated] | most declarations | Deprecation |
[Attribute] | a struct | Attributes of your own |
[Name], [Ignore], [Required], [Tag], [Untagged] | a property; an enum or its cases | JSON: attributes (the serialize module) |
[cli.Option], [cli.Positional] | a field | Declaring options as a struct |
A struct marked [Attribute] is an attribute of your own, which a static
block reads at compile time (see
Reflection and attributes). The built-in ones are
declared the same way, in the runtime, so the
reference lists each with its fields.