Derive Macro rocket::UriDisplayQuery

source ·
#[derive(UriDisplayQuery)]
{
    // Attributes available to this derive:
    #[field]
}
Expand description

Derive for the UriDisplay<Query> trait.

The UriDisplay<Query> derive can be applied to enums and structs. When applied to an enum, the enum must have at least one variant. When applied to a struct, the struct must have at least one field.

#[derive(UriDisplayQuery)]
enum Kind {
    A(String),
    B(usize),
}

#[derive(UriDisplayQuery)]
struct MyStruct {
    name: String,
    id: usize,
    kind: Kind,
}

Each field’s type is required to implement UriDisplay<Query>.

The derive generates an implementation of the UriDisplay<Query> trait. The implementation calls Formatter::write_named_value() for every named field, using the field’s name (unless overridden, explained next) as the name parameter, and Formatter::write_value() for every unnamed field in the order the fields are declared.

The derive accepts one field attribute: field, with the following syntax:

field := 'name' '=' '"' FIELD_NAME '"'
       | 'value' '=' '"' FIELD_VALUE '"'

FIELD_NAME := valid HTTP field name
FIELD_VALUE := valid HTTP field value

When applied to a struct, the attribute can only contain name and looks as follows:

#[derive(UriDisplayQuery)]
struct MyStruct {
    name: String,
    id: usize,
    #[field(name = "type")]
    #[field(name = "kind")]
    kind: Kind,
}

The field attribute directs that a different field name be used when calling Formatter::write_named_value() for the given field. The value of the name attribute is used instead of the structure’s actual field name. If more than one field attribute is applied to a field, the first name is used. In the example above, the field MyStruct::kind is rendered with a name of type.

The attribute can also be applied to variants of C-like enums; it may only contain value and looks as follows:

#[derive(UriDisplayQuery)]
enum Kind {
    File,
    #[field(value = "str")]
    #[field(value = "string")]
    String,
    Other
}

The field attribute directs that a different value be used when calling Formatter::write_named_value() for the given variant. The value of the value attribute is used instead of the variant’s actual name. If more than one field attribute is applied to a variant, the first value is used. In the example above, the variant Kind::String will render with a value of str.