visual 0.2.0

Use Display if available, Debug otherwise
Documentation
  • Coverage
  • 0%
    0 out of 9 items documented0 out of 0 items with examples
  • Size
  • Source code size: 8.58 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.69 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Links
  • Homepage
  • yds12/visual
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • yds12

visual

Use the Display trait if it's satisfied, fallback to Debug otherwise, and if neither are implemented use a default string value.

Why

The typical "nice" way to display things is via the Display trait. However, sometimes this trait is not available, but Debug is. Debug is easy to derive. In those cases it would be nice to use Debug as a fallback.

Usage

use visual::{vis, Visual};

fn main() {
    // The `vis!` macro wraps your type in such a way that it can decide which trait to
    // use: `Display`, `Debug` or neither
    printer(vis!("hello"));       // `&str` implements `Display`, so use it
    printer(vis!(vec![1, 2, 3])); // `Vec` does not, but it impls `Debug`, so we use that

    struct MyStruct;
    printer(vis!(MyStruct));      // `MyStruct` impls neither, so we use a default string value
}

fn printer<T>(t: Visual<T>) {        // Use the `Visual` wrapper around your type
    println!("{}", t.get_display()); // Use `get_display` to get a string representation of your type
}

If neither trait is implemented, the string representation will be the one defined by visual::get_non_displayable_string(). This default label can be initialized to a custom value once, by calling visual::set_non_displayable_string("value").

Credits

For the magic to work, I use the "autoderef hack" proposed by Lukas Kalbertodt, which in turn is based on David Tolnay's technique.

Links