5

Github Suggest borrowing if a trait implementation is found for &/&mut &...

 3 years ago
source link: https://github.com/rust-lang/rust/pull/85369
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Copy link

Contributor

FabianWolff commented 19 days ago

This pull request fixes #84973 by suggesting to borrow if a trait is not implemented for some type T, but it is for &T or &mut T. For instance:

trait Ti {}
impl<T> Ti for &T {}
fn foo<T: Ti>(_: T) {}

trait Tm {}
impl<T> Tm for &mut T {}
fn bar<T: Tm>(_: T) {}

fn main() {
    let a: i32 = 5;
    foo(a);

    let b: Box<i32> = Box::new(42);
    bar(b);
}

gives, on current nightly:

error[E0277]: the trait bound `i32: Ti` is not satisfied
  --> t2.rs:11:9
   |
3  | fn foo<T: Ti>(_: T) {}
   |           -- required by this bound in `foo`
...
11 |     foo(a);
   |         ^ the trait `Ti` is not implemented for `i32`

error[E0277]: the trait bound `Box<i32>: Tm` is not satisfied
  --> t2.rs:14:9
   |
7  | fn bar<T: Tm>(_: T) {}
   |           -- required by this bound in `bar`
...
14 |     bar(b);
   |         ^ the trait `Tm` is not implemented for `Box<i32>`

error: aborting due to 2 previous errors

whereas with my changes, I get:

error[E0277]: the trait bound `i32: Ti` is not satisfied
  --> t2.rs:11:9
   |
3  | fn foo<T: Ti>(_: T) {}
   |           -- required by this bound in `foo`
...
11 |     foo(a);
   |         ^
   |         |
   |         expected an implementor of trait `Ti`
   |         help: consider borrowing here: `&a`

error[E0277]: the trait bound `Box<i32>: Tm` is not satisfied
  --> t2.rs:14:9
   |
7  | fn bar<T: Tm>(_: T) {}
   |           -- required by this bound in `bar`
...
14 |     bar(b);
   |         ^
   |         |
   |         expected an implementor of trait `Tm`
   |         help: consider borrowing mutably here: `&mut b`

error: aborting due to 2 previous errors

In my implementation, I have added a "blacklist" to make these suggestions flexible. In particular, suggesting to borrow can interfere with other suggestions, such as to add another trait bound to a generic argument. I have tried to configure this blacklist to cause the least amount of test case failures, i.e. to model the current behavior as closely as possible (I only had to change one existing test case, and this change was quite clearly an improvement).


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK