Is bool::to_string() guaranteed to yield "true" and "false"?

Is it safe to replace (if b { "true" } else { "false" }).to_string() with b.to_string()? I believe the answer is yes, the strings will always be "true" and "false", nothing else, but I'm having trouble finding documentation that guarantees it.

Its not in the documentation, so you have to look at the source code:

#[stable(feature = "rust1", since = "1.0.0")]
impl Display for bool {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Display::fmt(if *self { "true" } else { "false" }, f)
    }
}

So yes, it will always be "true" or "false".

1 Like

The code shows that it currently returns "true" and "false", not that it always will, no?

1 Like

Changes to Display/ToString impls are considered breaking changes.

Here is a previous topic discussing whether changes to output of Display should be considered breaking:

Quote from this topic:

2 Likes

A related conversation came up about bool: FromStr last year: "TRUE" does not parse into boolean · Issue #101870 · rust-lang/rust · GitHub

Based on the decision there being "no, bool parses from "true" and "false" only", it seems implausible that the ToString for it would ever be anything else. (After all, .to_string().parse().unwrap() should always be a no-op.)

You could always send a PR adding such a guarantee to the docs, if you want a more explicit reason. Then libs-api would choose whether to provide it. (I'm 99.99% certain it would be uncontroversial.)

3 Likes

Is that an actual guideline or a statement of opinion ? I don't think I've always followed that rule for my own types.

It's an actual guideline; Display (therefore ToString) and FromStr should in general match.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.