【发布时间】:2021-11-17 01:14:52
【问题描述】:
当我这样做时
seq += u64::from(rhs);
一切正常。但我更喜欢rhs.into() 的语法,因为我目前正在使用,
error[E0283]: type annotations needed
--> src/sequence.rs:50:5
|
19 | seq += rhs.into();
| ^^ ---------- this method call resolves to `T`
| |
| cannot infer type for type parameter `T`
|
= note: cannot satisfy `_: Into<u64>`
= note: required because of the requirements on the impl of `AddAssign<_>` for `Sequence`
这种.into() 语法通常有效。为什么类型推断不适用于二元运算符+=,如果 LHS 仅实现 AddAssign<u64>,RHS 将强制执行?此外,除了使用from 向.into 提供编译器需要的这种类型信息的语法(如果可能的话)是什么?我已经尝试过.into::<u64>(rhs) 之类的东西,而且不工作。
我正在像这样实现AddAssign,
impl<T: Into<u64>> AddAssign<T> for Sequence {
fn add_assign(&mut self, rhs: T) {...}
}
和From 这样,
impl From<Sequence> for u64 {
fn from(seq: Sequence)-> u64 { ... }
}
【问题讨论】:
-
向 .into 提供编译器需要的这种类型信息的语法(如果可能的话)是什么?
Into::<u64>::into(rhs) -
哦,这很漂亮。我尝试了
.into::<u64>(rhs)和一堆其他不起作用的前突变。你能回答这个问题吗?也许解释成Into<u64>::into(rhs)在语法上与.into::<u64>(rhs)不同? -
泛型类型参数属于这里的trait而不是函数
标签: rust type-conversion operator-overloading binary-operators