[英]Rust: define generic of impl is not an Option
Can I say this implementation is not for Option<_>
or add priority for impl
?我可以说这个实现不适用于
Option<_>
或为impl
添加优先级吗?
I know I can add type to let y: Foo<_>
, but I want to use auto infer.我知道我可以添加类型
let y: Foo<_>
,但我想使用自动推断。
enum Foo<T> {
Value(T),
Some(T),
None,
}
// only for non-option T types.
impl<T> From<T> for Foo<T>
// where !Option<_> ?
{
fn from(value: T) -> Self {
Foo::Value(value)
}
}
impl<T> From<Option<T>> for Foo<T> {
fn from(value: Option<T>) -> Self {
match value {
Some(value) => Foo::Some(value),
None => Foo::None,
}
}
}
let the_string = "hello".to_string();
let the_string_option = Some("world".to_string());
let x: Foo<_> = the_string.into();
let y: Foo<_> = the_string_option.into();
let y: Foo<_> = the_string_option.into();
- ^^^^^^ cannot infer type
|
consider giving `y` the explicit type `with_name::tests::test_multi_value::Foo<_>`, with the type parameters specified
There is no problem with the code.代码没有问题。 But compiler do not know what implementation of
From
/ Into
to use, that is why it asks for the type hint.但是编译器不知道使用什么
From
/ Into
实现,这就是它要求类型提示的原因。
It would be solved if you ever use the variable ( y
in this case) somewhere were is supposed to be of the expected type:如果您曾经在某个应该是预期类型的地方使用变量(在这种情况下为
y
),它将得到解决:
...
let y = the_string_option.into();
fn foo(v: Foo<String>) {}
foo(y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.