Hello, and good morning / afternoon, depending on where you are.
I was trying to play around with opaque types, and I don't get why something like this don't work.
What is the exact meaning of opaque type and how does it differ from a generic type? Also is there any way of making this small example work?
Addendum: I know that opaque types can't currently be in trait implementations, but I don't really get the error message of the compiler.
use std::fmt::Display;
pub struct MyStruct<T: Display>(T);
pub trait MyTrait<'a> {
type Input;
fn do_something<T>(&self, input: Self::Input) -> MyStruct<T>
where
T: Display;
}
pub struct MyOtherStruct {
string: String,
}
impl MyOtherStruct {
fn make_upper(&self, input: &str) -> MyStruct<impl Display> {
MyStruct(input.to_uppercase())
}
}
impl<'a> MyTrait<'a> for MyOtherStruct {
type Input = &'a str;
fn do_something<T>(&self, input: Self::Input) -> MyStruct<T>
where
T: Display,
{
self.make_upper(input)
}
}
Compiler gives:
Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
--> src/lib.rs:29:9
|
18 | fn make_upper(&self, input: &str) -> MyStruct<impl Display> {
| ------------ the found opaque type
...
25 | fn do_something<T>(&self, input: Self::Input) -> MyStruct<T>
| - this type parameter ----------- expected `MyStruct<T>` because of return type
...
29 | self.make_upper(input)
| ^^^^^^^^^^^^^^^^^^^^^^ expected type parameter `T`, found opaque type
|
= note: expected struct `MyStruct<T>`
found struct `MyStruct<impl std::fmt::Display>`
= help: type parameters must be constrained to match other types
= note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters
error: aborting due to previous error