Diagnostics for conversions erroneously say that 'as' only works between primitive types.

2e29bad
Opened by Alexis Hunt at 2020-06-13 01:32:54

See https://play.rust-lang.org/?gist=7194dac428b4355e3f2872e9c0206800&version=stable

The note says "an as expression can only be used to convert between primitive types. Consider using the From trait", but as show by the expression Baz as i32, this is not true.

  1. Another example of this problem is here: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=068d6b1e9a91bb347071acc829d88dd7

    It demonstrates that it is possible to use as cast for conversion between Rc types, which are not primitive. Namely a Rc<Bar> type which implements FooObserver trait can be cast to Rc<dyn FooObserver> when cloning it.

    Arkadiusz Piekarz at 2019-08-03 17:03:01

  2. This note is also unhelpful with casting to &dyn Trait/&mut dyn Trait (playground):

    trait Trait {}
    
    struct Struct;
    impl Trait for Struct {}
    
    fn main() {
        let s = Struct; // or `let mut s = Struct;`
    
        let _ = s as &dyn Trait; // or `let _ = s as &mut dyn Trait;`
    }
    

    Compiler output:

    error[E0605]: non-primitive cast: `Struct` as `&dyn Trait`
     --> src/main.rs:9:13
      |
    9 |     let _ = s as &dyn Trait; // or `let _ = s as &mut dyn Trait;`
      |             ^^^^^^^^^^^^^^^
      |
      = note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
    

    I would imagine something like this:

    error[E0605]: non-primitive cast: `Struct` as `&dyn Trait`
     --> src/main.rs:9:13
      |
    9 |     let _ = s as &dyn Trait; // or `let _ = s as &mut dyn Trait;`
      |             ^^^^^^^^^^^^^^^
      |
      = help: try casting `&Struct` instead: `&s as &dyn Trait`
    

    See also related issue #44602.

    link ✦ at 2020-01-06 13:07:01