I wrote a type Wrapper<T>
which contains a value of T
:
struct Wrapper<T>(T);
I want a method to_wrap
which would allow me to write code like this, where b
is Wrapper<i32>
and c
is Wrapper<i32>
:
let a = 12i32;
let b = a.to_wrap();
let c = b.to_wrap();
I want v.to_wrap()
to always produce a Wrapper<T>
where T is NOT a Wrapper
. If v
is a Wrapper<T>
, v.to_wrap()
will also be a Wrapper<T>
with the same value.
The code I wrote closest to my idea is:
#![feature(specialization)]
#[derive(Debug)]
struct Wrapper<T>(T);
trait ToWrapper<W> {
fn to_wrap(self) -> W;
}
impl<T> ToWrapper<Wrapper<T>> for T {
default fn to_wrap(self) -> Wrapper<T> {
Wrapper(self)
}
}
impl<T> ToWrapper<Wrapper<T>> for Wrapper<T> {
fn to_wrap(self) -> Self {
self
}
}
fn main() {
let a = 1i32;
println!("{:?}", a);
let a = 1.to_wrap();
println!("{:?}", a);
let a: Wrapper<i32> = 1.to_wrap().to_wrap();
// let a = 1.to_wrap().to_wrap();
// boom with `cannot infer type`
println!("{:?}", a);
}
This has a compilation error if I erase the type annotation on from let a: Wrapper<i32> = 1.to_wrap().to_wrap()
:
error[E0282]: type annotations needed
--> src/main.rs:27:9
|
27 | let a = 1.to_wrap().to_wrap();
| ^
| |
| cannot infer type
| consider giving `a` a type
I want the Rust compiler to automatically derive the type of 1.to_wrap().to_wrap()
. How can I write the correct version, or why is it not possible to write it?