Conceptcore
Annotations
Also called annotation, attributes, attribute, metadata annotations, decorators.
Structured metadata attached to declarations in source code, such as @Override in Java or #[derive] in Rust, which a compiler, a tool or the running program reads.
- Applies to
- core-languages
Idea
A declaration in source code says what a program element is: a class with these fields, a method with these parameters. Tools often need more. A test runner must know which methods are tests. A serializer must know the name of a field in JSON. A compiler must know that a method should override another one. An annotation is a piece of structured data that the programmer attaches to a declaration for such a reader.
Java defines it this way: "An annotation is a marker which associates information with a program element, but has no effect at run time."1 The annotation does nothing by itself. Something else reads it and acts. There are three readers:
- The compiler. It reads the annotation while it compiles and checks or changes its output.
@Overridein Java,nodiscardin C++ and#[derive(Debug)]in Rust work this way.11412 - A tool at compile time. An annotation processor or a source generator reads the annotations and writes additional source files.4510
- The running program. A library reads the annotations through reflection and changes what it does. A web framework finds its request handlers this way. See Runtime reflection.
The name differs by language. Java and Kotlin say annotation. C#, C, C++ and Rust say attribute. Python has decorators, which look like Java annotations but are function calls that run when the definition runs.16 Go has struct tags, which are strings on fields.21
Before annotations, programs carried this information in other ways. JSR 175, the Java request that introduced them, describes "a growing trend towards annotating fields, methods, and classes as having particular attributes that indicate they should be processed in special ways by development tools, deployment tools, or run-time libraries". It names naming patterns such as getFoo and setFoo in JavaBeans as one such ad hoc mechanism.3 A naming pattern fails without a message when a name is misspelled. An annotation is a declared type, so the compiler checks its name and its arguments.
How it works
A typed declaration
In Java, an annotation is an instance of an annotation interface, declared with @interface.1 The elements of the interface are the parameters of the annotation, and they can have default values. The java example runtime declares this:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Command {
String value();
String help() default "";
}
Annotations on the annotation interface, called meta-annotations, control its use. @Target limits the kinds of declarations that the annotation can mark.1 @Retention controls how long the annotation lives.
A C# attribute is a class that derives from System.Attribute. Its constructor parameters are the positional parameters, and its public read-write fields and properties are the named parameters.8 By convention, the name of the class ends in Attribute, and code can leave out the suffix: [DllImport] is the same as [DllImportAttribute].7 AttributeUsage plays the role of @Target, and the csharp example usage shows the compile error when an attribute is put in the wrong place.
Rust, C and C++ do not let a program declare an attribute as a type. In Rust, "An attribute is a general, free-form metadatum that is interpreted according to name, convention, language, and compiler version."11 The compiler defines the built-in attributes, and procedural macros can define more.11 In C and C++, the standard defines a small set of attributes, and vendors add their own attributes with a vendor prefix.1415
Retention
An annotation can live in three places, and Java names them with RetentionPolicy:2
SOURCE: "Annotations are to be discarded by the compiler."CLASS: "Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time."RUNTIME: "Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively."
If an annotation interface has no @Retention, the compiler treats it as CLASS.1 This default surprises many programmers. The java example default-retention declares an annotation without @Retention, and reflection finds no annotated methods.
Kotlin has the same choice. @Retention "specifies whether the annotation is stored in the compiled class files and whether it's visible through reflection at runtime", and by default both are true.24 C# attributes add metadata to the program, and "you can query the attribute at run time by using a technique called reflection".7 C and C++ define no standard way to read an attribute at run time.
Attributes that the compiler interprets
Many standard attributes ask the compiler for a diagnostic or change what it emits.
- Checks. Java's
@Overridecauses a compile-time error if the method does not override a method of a supertype.1 The java exampleoverrideshows the classic case from the specification:equals(Point)overloadsequals(Object)and does not override it.1 - Warnings about results.
nodiscardin C and C++ and#[must_use]in Rust mark a value that the caller should use.141513 - Deprecation.
deprecatedin C and C++,@Deprecatedin Java,#[deprecated]in Rust andObsoletein C# mark an element whose use is discouraged.141139 In C#,Obsoletewith a second argument oftruemakes each use a compile error.9 - Conditional code. The Rust attribute
cfg"Controls conditional compilation".11 C#'sConditionalattribute makes the compiler leave out calls to a method when a preprocessing symbol is not defined.9 The csharp examplecustomshows a call that disappears. - Generated code. Rust's
derive"invokes one or more derive macros, allowing new items to be automatically generated for data structures".12 The rust examplederivegetsDebug,Clone,PartialEqandDefaultfrom one line.
C and C++ give their standard attributes optional semantics. In C, "Standard attributes specified by this document can be parsed but ignored by an implementation without changing the semantics of a correct program".15 In C++, removing one of the standard attributes from a correct program gives a program whose possible executions are a subset of those of the original.14 For nodiscard, both standards only recommend a warning.1415 The c and cpp examples nodiscard compile with -Werror, so the warning stops the build.
Annotation processors and source generators
An annotation processor is a plug-in for the compiler. In Java, the interface is javax.annotation.processing.Processor. "Annotation processing happens in a sequence of rounds." In each round, the compiler asks the processors to handle the annotations found on the source and class files of the previous round.4 The Filer interface "supports the creation of new files by an annotation processor", and the compiler processes the generated source files in a later round.5 JSR 269 defined this API.6
C# has the same idea in source generators, which "enable compile time metaprogramming, that is, code that can be created at compile time and added to the compilation".10 Kotlin has KSP: "With the KSP API, you can create processors that inspect static information about your source code and generate new code from it. The most common use case is generating code based on annotations."25 Rust's derive macros have the same role. A derive macro receives the token stream of the item, and the items that it returns are appended after the input item.29 See Syntactic macros.
None of the examples on this page runs a processor. A processor must be compiled before the code that it processes, and each example here is a single file.
Reading annotations at run time
A program that reads RUNTIME annotations uses reflection. The java example runtime collects the methods marked @Command, sorts them by name and calls them. The csharp example custom does the same with GetCustomAttribute. Go has no annotations, but a struct tag is a string that "becomes an attribute for all the fields in the corresponding field declaration". "The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored."21 The package encoding/json reads the key json in the go example tags.
Python decorators
Python's @ syntax looks like an annotation, but its meaning is different. "Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object."16 So this code:
@f1(arg)
@f2
def func(): pass
is "roughly equivalent to" func = f1(arg)(f2(func)).16 Classes take decorators in the same way.16 A decorator is a higher-order function, see Higher-order function. It can register the function, as command does in the python example registry. It can return a wrapper that adds behavior around each call, which is the Decorator pattern applied to a function. It can also change a class: @dataclass "examines the class to find fields", where "A field is defined as a class variable that has a type annotation", and it adds methods such as __init__ and __repr__.19
A decorator that returns a wrapper replaces the function. The name, the docstring and the other attributes that tools read are now those of the wrapper. The python example no-wraps prints wrapper None for the name and the docstring. functools.wraps copies __module__, __name__, __qualname__, __annotations__, __type_params__ and __doc__ from the original, and it adds __wrapped__, a reference to the original function.18 The python example wraps shows the fix.
The word annotation also has a meaning in Python, and it is not this one. A Python annotation is "A label associated with a variable, a class attribute or a function parameter or return value, used by convention as a type hint."20
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Absent | Decorators are a TC39 proposal at stage 2.7, not part of ECMAScript; Node.js rejects the syntax. Alternative: Call a function on the class or the method after its definition, or use a build tool that transforms decorators. |
| TypeScript | Native | TypeScript 5.0 implements the ECMAScript decorators proposal and type-checks it; no example file because Node.js type stripping does not transform decorators. Alternative: Experimental decorators with the compiler flag --experimentalDecorators. |
| Go | Idiom | |
| Rust | Native | |
| Kotlin | Native | Annotation classes with @Target and @Retention, readable through reflection or by KSP processors at compile time; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | SQL has no user-defined annotations on statements or tables. |
| Bash | Absent | A shell function has no metadata other than its name and body. |
| PowerShell | Native | Advanced functions use attributes such as [CmdletBinding()] and [Parameter()] on functions and parameters; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | HTML attributes are part of the markup itself, not metadata about program code. |
| CSS | Does not apply | Style rules have no declarations of program code to annotate. |
| Regular expressions | Does not apply | A pattern has no declarations to annotate. |
| Language | Verdict | Form |
|---|---|---|
| Java | native | @interface, @Target, @Retention; annotation processors; reflection |
| C# | native | classes derived from Attribute, AttributeUsage; source generators; reflection |
| Kotlin | native | annotation class, @Target, @Retention; KSP |
| Rust | native | #[...] and #![...]; derive; attributes from procedural macros |
| C++ | native | [[...]] with standard and vendor attributes |
| C | native | C23 [[...]] with standard and vendor attributes |
| TypeScript | native | decorators of the ECMAScript proposal |
| Python | idiom | decorators: functions applied when a definition runs |
| Go | idiom | struct tags read through reflect |
| JavaScript | absent | decorators are a proposal at stage 2.7 |
| PowerShell | native | [CmdletBinding()], [Parameter()] and validation attributes |
| Bash | absent | no metadata on functions |
| SQL | n/a | no user-defined annotations |
| Regex | n/a | no declarations |
| HTML/CSS | n/a | HTML attributes are markup, not metadata on code |
Java annotations apply to declarations. An annotation whose interface is applicable in type contexts, such as with @Target(ElementType.TYPE_USE), is a type annotation and applies to a type.1 An annotation on a local variable declaration is never kept in the class file, whatever its retention.1
C# attributes can apply to assemblies, modules, types, members, parameters and return values. A target prefix such as [assembly: ...] or [return: ...] selects the element.7
Kotlin annotations "are tags that you can use to attach metadata to elements in your code. Tools and frameworks process this metadata during compilation and runtime".24 No Kotlin example runs on this page, because kotlinc is not installed on the machine that recorded the examples.
Rust has inner attributes, #![...], which apply to the item that contains them, and outer attributes, #[...], which apply to the item that follows.11 The kinds are built-in attributes, attributes of procedural macros, helper attributes of derive macros and tool attributes.11 Lint attributes such as deny change the level of a lint, and the rust example must-use turns the lint unused_must_use into an error.13
C++ reserves attribute names that are not in a namespace for future standards, and "any such attribute-token that is not recognized by the implementation is ignored".14 An attribute that the standard defines but that is put on the wrong kind of entity makes the program ill-formed.14 C adopted the same syntax in C23 with the standard attributes deprecated, fallthrough, maybe_unused, nodiscard, noreturn, _Noreturn, unsequenced and reproducible.15
TypeScript 5.0 implemented the decorators of the ECMAScript proposal. The older form needs the compiler flag --experimentalDecorators.26 No TypeScript example runs on this page, because Node.js type stripping does not transform decorators. JavaScript does not have decorators yet. The TC39 proposal is at stage 2.7, and it describes decorators as "functions called on classes, class elements, or other JavaScript syntax forms during definition".27 PowerShell advanced functions use attributes such as [CmdletBinding()] and [Parameter()] on functions and parameters.28
from dataclasses import dataclass
COMMANDS = {}
def command(name):
def register(func):
COMMANDS[name] = func
return func
return register
@command("hello")
def hello():
return "hello, world"
@command("time")
def time_of_day():
return "noon"
@dataclass(frozen=True)
class Point:
x: int
y: int
for name in sorted(COMMANDS):
print(name, "->", COMMANDS[name]())
p = Point(1, 2)
print(p, p == Point(1, 2))
try:
p.x = 5
except AttributeError as e:
print(type(e).__name__)
hello -> hello, world
time -> noon
Point(x=1, y=2) True
FrozenInstanceError
A decorator is an expression after @. Python evaluates it when the function is defined, calls the result with the function, and binds the name to the return value. command("hello") returns register, which records the function and returns it unchanged. @dataclass reads the field annotations of the class and adds __init__, __repr__ and __eq__. With frozen=True, assignment to a field raises an exception.
This code runs but gives a wrong answer on purpose.
def logged(func):
def wrapper(*args, **kwargs):
print("calling", func.__name__)
return func(*args, **kwargs)
return wrapper
@logged
def area(w, h):
"""Return the area of a rectangle."""
return w * h
print(area(3, 4))
print(area.__name__, area.__doc__)
calling area
12
wrapper None
The decorator returns wrapper, so the name area now refers to wrapper. Its name and its docstring are those of wrapper. Tools that read them, such as help and test reports, show the wrong function.
import functools
def logged(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("calling", func.__name__)
return func(*args, **kwargs)
return wrapper
@logged
def area(w, h):
"""Return the area of a rectangle."""
return w * h
print(area(3, 4))
print(area.__name__, area.__doc__)
print(area.__wrapped__(5, 6))
calling area
12
area Return the area of a rectangle.
30
functools.wraps copies the name, the docstring and other attributes of func to wrapper, and it adds __wrapped__, a reference to the original function.
- Verdict: idiom. Python has no annotations in the sense of Java. A decorator is a function that the program calls when it defines a function or a class, so it can register, wrap or change the decorated object.
- In Python, the word annotation means something else: a type hint on a parameter, a return value or a variable.
#include <iostream>
#include <string>
[[nodiscard]] bool save(const std::string& data) {
return !data.empty();
}
[[deprecated("use describe")]] std::string old_describe(int level) {
return std::to_string(level);
}
std::string describe(int level) {
std::string out;
switch (level) {
case 2:
out += "high ";
[[fallthrough]];
case 1:
out += "on";
break;
default:
out = "off";
}
return out;
}
int main() {
[[maybe_unused]] int unused_in_release = 42;
if (save("data")) {
std::cout << "saved\n";
}
std::cout << describe(2) << " | " << describe(1) << " | " << describe(0) << "\n";
}
saved
high on | on | off
nodiscard asks for a warning if a caller drops the result. fallthrough says that the missing break is deliberate. maybe_unused silences the warning for a variable that a build does not use. deprecated causes a warning at each use, and this program has none.
This code does not compile, on purpose.
#include <iostream>
#include <string>
[[nodiscard("the result says if the data was saved")]] bool save(const std::string& data) {
return !data.empty();
}
int main() {
save("");
std::cout << "done\n";
}
The standard asks only for a warning when a program drops the result of a nodiscard call. This example compiles with -Werror, so the warning stops the build.
This code runs but gives a wrong answer on purpose.
#include <iostream>
#include <string>
[[nodiscrd]] bool save(const std::string& data) {
return !data.empty();
}
int main() {
save("");
std::cout << "done\n";
}
done
nodiscrd is not a standard attribute. An implementation ignores an attribute that it does not recognize, so the program compiles, the failed save goes unnoticed, and the program prints done. Compilers can warn about unknown attributes, but a warning does not stop the build.
- Verdict: native. Attributes are written
[[...]]. The standard attributes give hints and requests for diagnostics. Vendors add their own in a namespace, such asgnu::orclang::. - The standard attributes have optional semantics. If a correct program drops one of them, the set of possible executions is a subset of the executions of the original.
- C++ has no annotation that a program can read at run time.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.TreeMap;
public class Main {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Command {
String value();
String help() default "";
}
public static class Tool {
@Command(value = "hello", help = "print a greeting")
public String hello() {
return "hello, world";
}
@Command("time")
public String time() {
return "noon";
}
public String helper() {
return "not a command";
}
}
public static void main(String[] args) throws Exception {
Tool tool = new Tool();
Map<String, Method> commands = new TreeMap<>();
for (Method m : Tool.class.getDeclaredMethods()) {
Command c = m.getAnnotation(Command.class);
if (c != null) {
commands.put(c.value(), m);
}
}
for (Map.Entry<String, Method> e : commands.entrySet()) {
Method m = e.getValue();
String help = m.getAnnotation(Command.class).help();
System.out.println(e.getKey() + " -> " + m.invoke(tool) + " [help: \"" + help + "\"]");
}
}
}
hello -> hello, world [help: "print a greeting"]
time -> noon [help: ""]
@interface declares an annotation interface. @Retention(RetentionPolicy.RUNTIME) keeps the annotation in the class file and makes it visible to reflection. The program finds the annotated methods and calls them by the name in the annotation. helper has no annotation, so it is not a command. The TreeMap sorts the names, because getDeclaredMethods returns the methods in no particular order.
This code runs but gives a wrong answer on purpose.
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
public class Main {
@Target(ElementType.METHOD)
@interface Command {
String value();
}
public static class Tool {
@Command("hello")
public String hello() {
return "hello, world";
}
}
public static void main(String[] args) {
int found = 0;
for (Method m : Tool.class.getDeclaredMethods()) {
if (m.isAnnotationPresent(Command.class)) {
found++;
}
}
System.out.println("commands found: " + found);
}
}
commands found: 0
The annotation has no @Retention, so its retention policy is CLASS. The compiler writes it into the class file, but the virtual machine need not keep it at run time, and reflection does not see it. The program compiles, runs and finds no commands.
This code does not compile, on purpose.
public class Main {
static final class Point {
final int x;
final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Point other) {
return x == other.x && y == other.y;
}
}
public static void main(String[] args) {
System.out.println(new Point(1, 2).equals(new Point(1, 2)));
}
}
equals(Point) overloads equals(Object) and does not override it. Without the annotation, the program compiles, and code that calls equals(Object), such as a HashSet, still uses the method inherited from Object. With @Override, the compiler reports the mistake.
- Verdict: native. An annotation interface declares the elements,
@Targetlimits where the annotation can appear, and@RetentionchoosesSOURCE,CLASSorRUNTIME. - An annotation has no effect at run time by itself. A tool gives it meaning: the compiler for
@Override, an annotation processor at compile time, or reflection at run time. - An annotation processor runs inside the compiler and can generate source files. It needs a separate compilation step, so no processor runs on this page.
#include <stdio.h>
[[nodiscard("check the result")]] int save(const char *data) {
return data[0] != '\0';
}
[[deprecated("use describe")]] const char *old_describe(int level);
static void describe(int level) {
switch (level) {
case 2:
printf("high ");
[[fallthrough]];
case 1:
printf("on\n");
break;
default:
printf("off\n");
}
}
int main(void) {
[[maybe_unused]] int debug_level = 0;
if (save("data")) {
printf("saved\n");
}
describe(2);
describe(0);
return 0;
}
saved
high on
off
C23 adopted the [[...]] syntax and the standard attributes nodiscard, deprecated, fallthrough and maybe_unused, with the same meaning as in C++.
This code does not compile, on purpose.
#include <stdio.h>
[[nodiscard("check the result")]] int save(const char *data) {
return data[0] != '\0';
}
int main(void) {
save("");
printf("done\n");
return 0;
}
The standard encourages a diagnostic when a program discards the result of a nodiscard call. The example compiles with -Werror, so the diagnostic stops the build.
- Verdict: native. C23 has the
[[...]]attribute syntax, eight standard attributes and prefixed attributes for vendors, such asgnu::. - A standard attribute does not change the meaning of a correct program. An implementation can parse it and ignore it.
- C has no annotations that a program can read at run time.
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
[AttributeUsage(AttributeTargets.Method)]
class CommandAttribute : Attribute
{
public string Name { get; }
public string Help { get; set; } = "";
public CommandAttribute(string name)
{
Name = name;
}
}
class Tool
{
[Command("hello", Help = "print a greeting")]
public string Hello() => "hello, world";
[Command("time")]
public string Time() => "noon";
public string Helper() => "not a command";
}
class Program
{
[Conditional("TRACE_ON")]
static void Trace(string message) => Console.WriteLine("trace: " + message);
static void Main()
{
var tool = new Tool();
var commands = typeof(Tool).GetMethods()
.Select(m => (Method: m, Attr: m.GetCustomAttribute<CommandAttribute>()))
.Where(p => p.Attr != null)
.OrderBy(p => p.Attr!.Name);
foreach (var (method, attr) in commands)
{
Trace("calling " + method.Name);
Console.WriteLine($"{attr!.Name} -> {method.Invoke(tool, null)} [help: \"{attr.Help}\"]");
}
}
}
hello -> hello, world [help: "print a greeting"]
time -> noon [help: ""]
An attribute is a class that derives from Attribute. The constructor parameter name is a positional parameter, and the property Help is a named parameter. [Command(...)] drops the suffix Attribute. The program reads the attributes through reflection. Trace has the Conditional attribute, and the symbol TRACE_ON is not defined, so the compiler leaves out each call to it.
This code does not compile, on purpose.
using System;
class Account
{
[Obsolete("use Deposit", true)]
public void Add(decimal amount) => Balance += amount;
public void Deposit(decimal amount) => Balance += amount;
public decimal Balance { get; private set; }
}
class Program
{
static void Main()
{
var a = new Account();
a.Add(10m);
Console.WriteLine(a.Balance);
}
}
Obsolete with true as its second argument makes each use of the method a compile error. Without the second argument, the use is a warning.
This code does not compile, on purpose.
using System;
[AttributeUsage(AttributeTargets.Method)]
class CommandAttribute : Attribute
{
}
[Command]
class Tool
{
}
class Program
{
static void Main()
{
Console.WriteLine(new Tool());
}
}
AttributeUsage limits the attribute to methods. The program puts it on a class, and the compiler rejects it.
- Verdict: native. Attributes are classes that derive from
System.Attribute. The compiler stores them in the metadata of the assembly, and reflection reads them at run time. - Some attributes change what the compiler does:
Obsoleteadds a warning or an error, andConditionalremoves calls. - Source generators read attributes at compile time and add source files, in the same role as Java annotation processors.
package main
import (
"encoding/json"
"fmt"
"reflect"
)
type User struct {
Name string `json:"name"`
Email string `json:"email,omitempty"`
Password string `json:"-"`
}
func main() {
u := User{Name: "Ada", Password: "secret"}
out, err := json.Marshal(u)
if err != nil {
panic(err)
}
fmt.Println(string(out))
t := reflect.TypeOf(u)
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
fmt.Printf("%s: %q\n", f.Name, f.Tag.Get("json"))
}
}
{"name":"Ada"}
Name: "name"
Email: "email,omitempty"
Password: "-"
A struct tag is a string after a field. The language ignores it, and a package reads it through reflect. encoding/json uses the json key: name renames the field, omitempty leaves out an empty value, and - leaves out the field.
This code runs but gives a wrong answer on purpose.
package main
import (
"encoding/json"
"fmt"
)
type User struct {
Name string `json: "name"`
}
func main() {
out, err := json.Marshal(User{Name: "Ada"})
if err != nil {
panic(err)
}
fmt.Println(string(out))
}
{"Name":"Ada"}
The tag has a space after the colon, so it does not have the conventional key:"value" format. The compiler accepts any string, and the result of Tag.Get for such a tag is unspecified. Here encoding/json does not find the key and uses the field name Name. go vet reports tags that do not follow the format.
- Verdict: idiom. Go has no annotations. Struct tags attach strings to fields, and a package gives them meaning through
reflect. - A comment
//go:generatetells the toolgo generatewhich command to run. The compiler does not run it.
#[derive(Debug, Clone, PartialEq, Default)]
struct Point {
x: i32,
y: i32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Level {
Low,
High,
}
fn main() {
let a = Point { x: 1, y: 2 };
let b = a.clone();
println!("{:?}", a);
println!("a == b: {}", a == b);
println!("default: {:?}", Point::default());
println!("Low < High: {}", Level::Low < Level::High);
#[cfg(target_pointer_width = "64")]
println!("64-bit target");
}
Point { x: 1, y: 2 }
a == b: true
default: Point { x: 0, y: 0 }
Low < High: true
64-bit target
#[derive(...)] asks the compiler to write the implementations of the listed traits. PartialEq compares the fields one by one, Debug prints the fields, and PartialOrd on an enum orders the variants by their position. #[cfg(...)] keeps the statement only when the condition holds for the target.
This code does not compile, on purpose.
struct Point {
x: i32,
y: i32,
}
fn main() {
let a = Point { x: 1, y: 2 };
let b = Point { x: 1, y: 2 };
println!("{}", a == b);
}
Rust gives a struct no equality by default. Without #[derive(PartialEq)] or a hand-written impl, == is a compile error (E0369).
This code does not compile, on purpose.
use std::marker::PhantomData;
struct Meters;
#[derive(Clone)]
struct Id<T> {
value: u32,
unit: PhantomData<T>,
}
fn main() {
let a: Id<Meters> = Id { value: 7, unit: PhantomData };
let b = a.clone();
println!("{}", b.value);
}
The derived impl requires T: Clone, even though PhantomData<T> is Clone for each T. Meters is not Clone, so a.clone() does not exist. Write the impl Clone by hand, or derive Clone for Meters too.
This code does not compile, on purpose.
#![deny(unused_must_use)]
#[must_use = "the new balance is the result"]
fn deposit(balance: u64, amount: u64) -> u64 {
balance + amount
}
fn main() {
let balance = 100;
deposit(balance, 50);
println!("{balance}");
}
#[must_use] marks a value that the caller should use. Discarding it triggers the lint unused_must_use, which is a warning by default. The attribute #![deny(unused_must_use)] changes the lint level for the crate, so the warning becomes an error.
- Verdict: native. Attributes are written
#[...]on the item that follows or#![...]on the enclosing item. Built-in attributes control the compiler, andderiveruns derive macros that generate trait implementations. - Procedural macros can define new attributes and new derives. They live in a separate crate, so no procedural macro runs on this page.
Variations and related ideas
- Naming conventions. Before annotations, Java tools used patterns in names, such as
getFooandsetFooin JavaBeans.3 The compiler cannot check such a pattern. - Doc comment tags. JSR 175 considered "a doc comment tag @meta" as one possible syntax for the metadata facility.3
- Macros. A Rust attribute macro receives the tokens of the item. "The item to which the attribute is applied is replaced by the zero or more items in the returned TokenStream."29 An annotation processor in Java can only add files.5 See Syntactic macros.
- Reflection. An annotation with run-time retention is useful only with reflection. See Runtime reflection.
Pitfalls
The default retention hides the annotation
A Java annotation without @Retention has the retention CLASS, and reflection cannot see it.12 A framework that looks for it finds nothing and reports no error. The java example default-retention prints commands found: 0. Add @Retention(RetentionPolicy.RUNTIME) to each annotation that a program reads at run time.
A misspelled attribute
C++ ignores an attribute that the implementation does not recognize.14 The cpp example typo writes nodiscrd, and the program compiles and runs without the check. In Java, the name in an annotation "must name an accessible annotation interface (§6.6), or a compile-time error occurs".1
A malformed struct tag
A Go struct tag is a free string. By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs.22 If a tag does not have this format, the value that Get and Lookup return is unspecified.22 The go example bad-tag has a space after the colon, and encoding/json uses the field name Name. The analyzer structtag of go vet checks "that struct field tags conform to reflect.StructTag.Get".23
A wrapper that hides the function
A Python decorator that returns a different function replaces the name and the docstring that tools see. Use functools.wraps on each wrapper.18
Bounds from derive
A derived implementation adds bounds on each type parameter. The Reference example shows impl<T: PartialEq> PartialEq for Foo<T>.12 The rust example derive-bound derives Clone for Id<T> with a PhantomData<T> field. The derived impl requires T: Clone, so Id<Meters> has no clone method. Write the impl by hand when the bound is wrong.
Behavior that the reader cannot see
An annotation can change behavior a long way from the code that it marks. A processor generates classes that are not in the source tree, and a framework calls methods that no code calls directly. Keep the number of annotations that change behavior small, and document what reads each one.
Cost
- Compile time. Processors, source generators and derive macros run in each build. They add time to compilation.
- Run time. Annotations with run-time retention are data in the binary. Reading them uses reflection, with the costs that Runtime reflection describes.
- Size. Metadata kept for run time increases the size of the program.
- Clarity. A short annotation can stand for a large amount of generated or framework code. The reader must know the processor or the framework to know what the program does.
History
- 2003. PEP 318 proposed decorators for Python functions and methods. It was created on 5 June 2003, for Python 2.4.17
- 2004. JSR 175, with Joshua Bloch as specification lead, reached final release on 30 September 2004.3 The Java API marks
java.lang.annotation.RetentionPolicywith "Since: 1.5".2 - 2006. JSR 269, the Pluggable Annotation Processing API, reached final release on 11 December 2006.6 The Java API marks
Processorwith "Since: 1.6".4 - C++11. The C++ standard lists, as a change from C++ 2003, that "Names of attribute identifiers may not be used as macro names". C++ 2003 code that defines
carries_dependencyornoreturnas a macro is invalid.14 - 2023. TypeScript 5.0, announced on 16 March 2023, implemented the decorators of the ECMAScript proposal.26
- C23. C added the attribute feature with
deprecated,fallthrough,maybe_unused,nodiscard,noreturn,unsequencedandreproducible.15
References
- The Java Language Specification, Java SE 25 Edition, Chapter 9 Interfaces, 9.6 Annotation Interfaces; 9.6.4.1 @Target; 9.6.4.2 @Retention; 9.6.4.4 @Override; 9.7 Annotations
- Java SE 25 API, java.lang.annotation.RetentionPolicy, Enum Constant Summary; Since
- JSR 175, A Metadata Facility for the Java Programming Language, Description; Stage timeline (Final Release, 30 Sep 2004); Section 1 Identification; Section 2.1
- Java SE 25 API, javax.annotation.processing.Processor, the interface description; Since
- Java SE 25 API, javax.annotation.processing.Filer, the interface description
- JSR 269, Pluggable Annotation Processing API, Description; Stage timeline (Final Release, 11 Dec 2006)
- C# documentation, Attributes and reflection, the introduction and the list of properties; Work with attributes; Attribute parameters
- C# documentation, Create custom attributes, the first paragraph and the AuthorAttribute example
- C# language reference, Attributes interpreted by the compiler, Miscellaneous attributes, Conditional attribute; Obsolete and Deprecated attribute
- Source Generators overview, the first paragraphs
- The Rust Reference, Attributes, attributes.intro; attributes.inner; attributes.outer; attributes.kind
- The Rust Reference, Derive, attributes.derive.intro and its example
- The Rust Reference, Diagnostic attributes, attributes.diagnostics.lint.level; lint.deny; deprecated.intro; must_use.intro; must_use.type
- N4950, Working Draft, Standard for Programming Language C++ (the C++23 draft), 9.12.1 [dcl.attr.grammar] paragraphs 1, 5 and 6 with Note 5; 9.12.5 [dcl.attr.deprecated]; 9.12.9 [dcl.attr.nodiscard] paragraphs 1 and 4; C.5.7 paragraph 5
- N3220, working draft of ISO/IEC 9899:2024 (C23), 6.7.13.2 General, paragraphs 2 and 3 and footnote 173; 6.7.13.3 The nodiscard attribute; M.1 Attribute Changes; M.2 Fifth Edition
- The Python Language Reference, 8 Compound statements, 8.7 Function definitions (decorator expressions); 8.8 Class definitions
- PEP 318, Decorators for Functions and Methods, the header (Created 05-Jun-2003, Python-Version 2.4)
- The Python Standard Library, functools, update_wrapper; wraps
- The Python Standard Library, dataclasses, the introduction; the dataclass decorator; Frozen instances
- Python Glossary, annotation
- The Go Programming Language Specification, Struct types, the paragraph on tags
- Go standard library, package reflect, type StructTag; StructTag.Get; StructTag.Lookup
- Go command documentation, cmd/vet, the list of analyzers, structtag
- Kotlin documentation, Annotations, the introduction; Usage (meta-annotations @Target and @Retention)
- Kotlin Symbol Processing API, the introduction
- Daniel Rosenwasser, Announcing TypeScript 5.0, TypeScript Blog, 16 March 2023, Decorators; Differences with Experimental Legacy Decorators
- TC39, Decorators proposal, the README header (Stage 2.7) and Introduction
- PowerShell documentation, about_Functions_Advanced_Parameters, Long description; Parameter declaration; Attributes of parameters
- The Rust Reference, Procedural macros, macro.proc.derive (the input and output token streams); macro.proc.attribute
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag VZD8YG Edit this page History Report an error Markdown