[英]How and when to use the generic type parameter in impl block in Rust?
[英]Rust: define generic of impl is not an Option
我可以說這個實現不適用於Option<_>
或為impl
添加優先級嗎?
我知道我可以添加類型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
代碼沒有問題。 但是編譯器不知道使用什么From
/ Into
實現,這就是它要求類型提示的原因。
如果您曾經在某個應該是預期類型的地方使用變量(在這種情況下為y
),它將得到解決:
...
let y = the_string_option.into();
fn foo(v: Foo<String>) {}
foo(y)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.