Remix.run Logo
worldsayshi 4 days ago

Does Rust not have built in Traits for string representations (like Show) or json representations of data?

dathinab 4 days ago | parent | next [-]

it has Display and Debug trait

both require a `fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>` function

while they work the same semantically it's "convert to string for displaying" and convert to string for debugging" (where debugging could be log messages, or print line debugging etc. by default debug for strings will do string escaping and for structs does print the structure/fields/type name in some semi standard way).

the Formatter is mostly just a string writer/sink, which also exposes a fixed set of formatting options and some utility methods

if a type implements Display through stuff I will skip over you then can also write `instance_of_type.to_string()` and get a string.

This trait are used in the default formatting mechanism used by e.g. `println!()` which other libraries (e.g. log) can use through `format!` and some other more internal/95% of case you don't need to know stuff. E.g. `println!("{a}, {a:?}, {a:#?}")` will in order print the display formatting of a, the debug formatting of a and then the alternative debug formatting (if there is one, else the normal one). And other options like pad left, floating point format options etc. exist too.

Through it should be noted that rust doesn't contain build in serialization, through nearly everything uses the library/traits/types from `serde` for that.

johnisgood 3 days ago | parent [-]

Only if Rust did not have so much symbol soup... :/ It is a bit too much for me, personally. If you are accustomed to it, it is probably not a big deal for you anymore, but for someone who does not know Rust as well, it could be a deal-breaker, which is why I would still rather prefer reference implementations in C, not Rust. Do not hide things from me!

tstenner 3 days ago | parent [-]

To be honest the few rust formatting options are easier to remember and more logical than the printf placeholders, e.g. ? for debugging, x for hex, X for upper case hex etc.

bonzini 4 days ago | parent | prev | next [-]

String representations are obtained with the Display trait, which automatically results in an implementation of to_string() as well.

danielheath 4 days ago | parent | prev [-]

Those are in (widely used) packages like serde