alloc: Add Borrow impls for &String, &mut String, &Vec, and &mut Vec#45808
alloc: Add Borrow impls for &String, &mut String, &Vec, and &mut Vec#45808erickt wants to merge 1 commit intorust-lang:masterfrom
Conversation
|
r? @dtolnay (rust_highfive has picked a reviewer for you, use r? to override) |
This patch addresses a small papercut, where the auto-ref/deref
does not work well with generic types. One small example of this
is:
```rust
use std::borrow::Borrow;
fn foo<T: Borrow<[usize]>>(x: T) {
println!("{:?}", x.borrow());
}
fn main() {
let x = vec![1, 2, 3];
foo(&x);
}
```
Without this patch, rust will error with:
```
error[E0277]: the trait bound `&std::vec::Vec<{integer}>: std::borrow::Borrow<[usize]>` is not satisfied
--> foo.rs:9:5
|
9 | foo(&x);
| ^^^ the trait `std::borrow::Borrow<[usize]>` is not implemented for `&std::vec::Vec<{integer}>`
|
= help: the following implementations were found:
<std::vec::Vec<T> as std::borrow::Borrow<[T]>>
= note: required by `foo`
error: aborting due to previous error
```
This forces users to use `x.as_slice()` to get the code to compile.
This patch then implements the following to cut down on unnecessary
line noise:
* `Borrow<str>` for `&String`, `&mut String`
* `BorrowMut<str>` for `String` and `&mut String`
* `Borrow<[T]>` for `&Vec<T>` and `&mut Vec<T>`
* `BorrowMut<[T]>` for `&mut Vec<T>`
|
This may be made redundant by one of the ergonomics experiments, specifically the ones addressing RFC 2147. |
dtolnay
left a comment
There was a problem hiding this comment.
Is BorrowMut<str> for String ever useful? I think the only way to use &mut str is make_ascii_uppercase.
For the others, is this something specific to &String and &Vec or do we ideally want it for everything else, &Cow, &Box, &Rc, &PathBuf, &CString, &[T; N], etc?
I would be inclined to avoid jumping the gun and give the ergonomics folks a chance to address this in a better way if possible.
|
Yeah, this might be a little too much of a papercut. I wrote this a while ago, and I'm having trouble tracking down why I really wanted this :) I also havne't found many examples where this would clean things up, so I'll close it, and hopefully the ergonomics folks will find a more all-encompassing solution. |
This patch addresses a small papercut, where the auto-ref/deref
does not work well with generic types. One small example of this
is:
Without this patch, rust will error with:
This forces users to use
x.as_slice()to get the code to compile.This patch then implements the following to cut down on unnecessary
line noise:
Borrow<str>for&String,&mut StringBorrowMut<str>forStringand&mut StringBorrow<[T]>for&Vec<T>and&mut Vec<T>BorrowMut<[T]>for&mut Vec<T>