Skip to content

Commit 6a09a85

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 550e035 commit 6a09a85

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
@@ -931,6 +931,15 @@ pub use macros::Debug;
931931
/// [tostring]: ../../std/string/trait.ToString.html
932932
/// [tostring_function]: ../../std/string/trait.ToString.html#tymethod.to_string
933933
///
934+
/// # Completeness and parseability
935+
///
936+
/// `Display` for a type might not necessarily be a lossless or complete representation of the type.
937+
/// It may omit internal state, precision, or other information the type does not consider important
938+
/// for user-facing output, as determined by the type. As such, the output of `Display` might not be
939+
/// possible to parse, and even if it is, the result of parsing might not exactly match the original
940+
/// value. Calling `.parse()` on the output from `Display` is usually a mistake, unless the type has
941+
/// provided and documented additional guarantees about its `Display` and `FromStr` implementations.
942+
///
934943
/// # Internationalization
935944
///
936945
/// 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
@@ -752,6 +752,15 @@ unsafe impl SliceIndex<str> for ops::RangeToInclusive<usize> {
752752
/// parse an `i32` with `FromStr`, but not a `&i32`. You can parse a struct that
753753
/// contains an `i32`, but not one that contains an `&i32`.
754754
///
755+
/// # Input format
756+
///
757+
/// The input format expected by a type's `FromStr` implementation depends on the type. Check the
758+
/// type's documentation for the input formats it knows how to parse. Note that the input format of
759+
/// a type's `FromStr` implementation might not necessarily accept the output format of its
760+
/// `Display` implementation; thus, calling `.parse()` on the output from `Display` is usually a
761+
/// mistake, unless the type has provided and documented additional guarantees about its `Display`
762+
/// and `FromStr` implementations.
763+
///
755764
/// # Examples
756765
///
757766
/// Basic implementation of `FromStr` on an example `Point` type:

0 commit comments

Comments
 (0)