[英]How to add trait bound to a non-generic type?
我有這個簡單的通用 function:
fn add_five<T: Into<i32>>(t: T) -> i32 {
5_i32 + t.into()
}
我想使用From
特征而不是Into
特征來表達,但是我嘗試重構:
fn add_five<T, i32: From<T>>(t: T) -> i32 {
5_i32 + <i32 as From<T>>::from(t)
}
引發此編譯錯誤:
error[E0277]: cannot add `i32` to `i32`
--> src/main.rs:24:11
|
| 5_i32 + <i32 as From<T>>::from(t)
| ^ no implementation for `i32 + i32`
|
= help: the trait `Add<i32>` is not implemented for `i32`
這很令人困惑,因為標准庫中確實有一個impl Add<i32> for i32
,那么真正的問題是什么?
添加綁定到非泛型類型的特征只能通過 where 子句完成:
fn add_five<T>(t: T) -> i32
where
i32: From<T> // now compiles!
{
5_i32 + <i32 as From<T>>::from(t)
}
<T, i32: From<T>>
失敗的原因是編譯器將<>
中使用的所有名稱解析為泛型類型參數的標識符。
錯誤消息令人困惑,因為當i32
引用具體的 32 位簽名 integer 類型與同名泛型類型參數的函數本地標識符時,編譯器沒有說明這一點(現在它也隱藏了具體的 integer 類型)。
這是錯誤消息,但添加了說明:
error[E0277]: cannot add `i32` (generic type) to `i32` (concrete integer type)
--> src/main.rs:24:11
|
| 5_i32 + <i32 (generic type) as From<T>>::from(t)
| ^ no implementation for `i32 (concrete integer type) + i32 (generic type)`
|
= help: the trait `Add<i32 (generic type)>` is not implemented for `i32` (concrete integer type)
或者用令人困惑的模棱兩可的i32
代替更傳統的U
作為泛型類型:
error[E0277]: cannot add `U` to `i32`
--> src/main.rs:24:11
|
| 5_i32 + <U as From<T>>::from(t)
| ^ no implementation for `i32 + U`
|
= help: the trait `Add<U>` is not implemented for `i32`
解決方法是簡單地將邊界移動到 where 子句中,如上所述,以避免意外地將i32
聲明為泛型類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.