Skip to content

Commit 1cfed0d

Browse files
committed
be more direct about borrow requirenments
1 parent 7641873 commit 1cfed0d

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

src/libcore/borrow.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@
3232
/// on the identical behavior of these additional trait implementations.
3333
/// These traits will likely appear as additional trait bounds.
3434
///
35+
/// In particular `Eq`, `Ord` and `Hash` must be equivalent for
36+
/// borrowed and owned values: `x.borrow() == y.borrow()` should give the
37+
/// same result as `x == y`.
38+
///
3539
/// If generic code merely needs to work for all types that can
3640
/// provide a reference to related type `T`, it is often better to use
3741
/// [`AsRef<T>`] as more types can safely implement it.

src/libcore/convert.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -105,11 +105,13 @@ pub const fn identity<T>(x: T) -> T { x }
105105
/// `&T` or write a custom function.
106106
///
107107
///
108-
/// `AsRef` is very similar to, but serves a slightly different purpose than [`Borrow`]:
108+
/// `AsRef` has the same signature as [`Borrow`], but `Borrow` is different in few aspects:
109109
///
110-
/// - Use `AsRef` when the goal is to simply convert into a reference
111-
/// - Use `Borrow` when the goal is related to writing code that is agnostic to
112-
/// the type of borrow and whether it is a reference or value
110+
/// - Unlike `AsRef`, `Borrow` has a blanket impl for any `T`, and can be used to accept either
111+
/// a reference or a value.
112+
/// - `Borrow` also requires that `Hash`, `Eq` and `Ord` for borrowed value are
113+
/// equivalent to those of the owned value. For this reason, if you want to
114+
/// borrow only a single field of a struct you can implement `AsRef`, but not `Borrow`.
113115
///
114116
/// [`Borrow`]: ../../std/borrow/trait.Borrow.html
115117
///

0 commit comments

Comments
 (0)