Skip to content

Commit 252ad18

Browse files
committed
Improve the documentation of Display and FromStr, and their interactions
In particular: - `Display` is not necessarily lossless - The output of `Display` might not be parseable by `FromStr`, and might not produce the same value if it is. - Calling `.parse()` on the output of `Display` is usually a mistake unless a type's documented output and input formats match. - The input formats accepted by `FromStr` depend on the type.
1 parent a124fb3 commit 252ad18

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

library/core/src/fmt/mod.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -928,6 +928,15 @@ pub use macros::Debug;
928928
/// [tostring]: ../../std/string/trait.ToString.html
929929
/// [tostring_function]: ../../std/string/trait.ToString.html#tymethod.to_string
930930
///
931+
/// # Completeness and parseability
932+
///
933+
/// `Display` for a type might not necessarily be a lossless or complete representation of the type.
934+
/// It may omit internal state, precision, or other information the type does not consider important
935+
/// for user-facing output, as determined by the type. As such, the output of `Display` might not be
936+
/// possible to parse, and even if it is, the result of parsing might not exactly match the original
937+
/// value. Calling `.parse()` on the output from `Display` is usually a mistake, unless the type has
938+
/// provided and documented additional guarantees about its `Display` and `FromStr` implementations.
939+
///
931940
/// # Internationalization
932941
///
933942
/// Because a type can only have one `Display` implementation, it is often preferable

library/core/src/str/traits.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -756,6 +756,15 @@ unsafe impl SliceIndex<str> for ops::RangeToInclusive<usize> {
756756
/// parse an `i32` with `FromStr`, but not a `&i32`. You can parse a struct that
757757
/// contains an `i32`, but not one that contains an `&i32`.
758758
///
759+
/// # Input format
760+
///
761+
/// The input format expected by a type's `FromStr` implementation depends on the type. Check the
762+
/// type's documentation for the input formats it knows how to parse. Note that the input format of
763+
/// a type's `FromStr` implementation might not necessarily accept the output format of its
764+
/// `Display` implementation; thus, calling `.parse()` on the output from `Display` is usually a
765+
/// mistake, unless the type has provided and documented additional guarantees about its `Display`
766+
/// and `FromStr` implementations.
767+
///
759768
/// # Examples
760769
///
761770
/// Basic implementation of `FromStr` on an example `Point` type:

0 commit comments

Comments
 (0)