Rust: Option<T> should impl Display

Created on 16 Jan 2018  路  10Comments  路  Source: rust-lang/rust

Option<T> should impl Display so that it renders as "Some(x)" where x is using T's Display impl.

C-feature-request T-libs

Most helpful comment

@Boscop You may want the Debug trait (which is implemented for Option<T> when T is Debug)? The Debug formatting syntax is just two extra characters:

fn main() {
    println!("{:?}", Some(42)); // prints `Some(42)`
}

All 10 comments

Why?

I disagree; Some doesn't seem like something we should assume the user wants to expose to the "public." Arguably this isn't really something that the standard library should support, though a crate could easily do so.

Some(x) doesn't really look suitable for end-user consumption

@Mark-Simulacrum But another crate can't do it because of orphan rules:
https://play.rust-lang.org/?gist=8785d227d9fab78aa38e336eee721b88&version=nightly

@Boscop You may want the Debug trait (which is implemented for Option<T> when T is Debug)? The Debug formatting syntax is just two extra characters:

fn main() {
    println!("{:?}", Some(42)); // prints `Some(42)`
}

Like @zackmdavis said, I think you're better off with the Debug trait. Take for instance a Option<&str>, here is how few of those would display:

  • Some("Option") -> "Some(Option)"
  • Some("") -> "Some()"
  • Some("UdpSocket") -> "Some(UdpSocket)"

This doesn't seem very intuitive to me.

Something "plausible" would be to impl Display for Option<&str> and the likes, where Some("some string") would display as some string and None would be displayed as nothing (0 characters). But in anycase, I think this is too specific to be in the standard library.

@zackmdavis @Cobrand I'm aware of that but I need to render using the Display impl of T, not its Debug impl..
@Mark-Simulacrum Thanks, I guess I will use that for now..

I think only way to provide valid implementation for any type is using a trait like OptionDisplay and implement Display for Option where T: OptionDisplay.

Although almost all types in std cannot implement it, it would be quite useful for newtype structs.

Was this page helpful?
0 / 5 - 0 ratings