Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement display-bound attribute for derive-Display macro (#93) #97

Merged
57 changes: 56 additions & 1 deletion doc/display.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,65 @@ i.e. `_0`, `_1`, `_2`, etc.
The syntax does not change, but the name of the attribute is the snake case version of the trait.
E.g. `Octal` -> `octal`, `Pointer` -> `pointer`, `UpperHex` -> `upper_hex`.

# Generic data types

When deriving `Display` (or other formatting trait) for a generic struct/enum, all generic type
arguments used during formatting are bound by respective formatting trait.

E.g., for a structure `Foo` defined like this:
```rust
#[macro_use] extern crate derive_more;

trait Trait {
type Type;
}

#[derive(Display)]
#[display(fmt = "{} {} {:?} {:p}", a, b, c, d)]
struct Foo<'a, T1, T2: Trait, T3> {
a: T1,
b: <T2 as Trait>::Type,
c: Vec<T3>,
d: &'a T1,
}
```

The following where clauses would be generated:
* `T1: Display + Pointer`
* `<T2 as Trait>::Type: Debug`
* `Bar<T3>: Display`

## Custom trait bounds

Sometimes you may want to specify additional trait bounds on your generic type parameters, so that they
could be used during formatting. This can be done with a `#[display(bound = "...")]` attribute.

`#[display(bound = "...")]` accepts a single string argument in a format similar to the format
used in angle bracket list: `T: MyTrait, U: Trait1 + Trait2`.

Only type parameters defined on a struct allowed to appear in bound-string and they can only be bound
by traits, i.e. no lifetime parameters or lifetime bounds allowed in bound-string.

```rust
#[macro_use] extern crate derive_more;

trait MyTrait {
fn my_function(&self) -> i32;
}

#[derive(Display)]
#[display(bound = "T: MyTrait, U: ::std::fmt::Display")]
#[display(fmt = "{} {}", "a.my_function()", "b.to_string()")]
JelteF marked this conversation as resolved.
Show resolved Hide resolved
struct MyStruct<T, U> {
a: T,
b: U,
}
```

# Example usage

```rust
# #[macro_use] extern crate derive_more;
#[macro_use] extern crate derive_more;

use std::path::PathBuf;

Expand Down
Loading