【问题标题】:From and Into with binary std::ops: cannot infer type for type parameter `T`?二进制 std::ops 的 From 和 Into:无法推断类型参数“T”的类型?
【发布时间】: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&lt;u64&gt;,RHS 将强制执行?此外,除了使用from .into 提供编译器需要的这种类型信息的语法(如果可能的话)是什么?我已经尝试过.into::&lt;u64&gt;(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::&lt;u64&gt;::into(rhs)
  • 哦,这很漂亮。我尝试了.into::&lt;u64&gt;(rhs) 和一堆其他不起作用的前突变。你能回答这个问题吗?也许解释成Into&lt;u64&gt;::into(rhs)在语法上与.into::&lt;u64&gt;(rhs)不同?
  • 泛型类型参数属于这里的trait而不是函数

标签: rust type-conversion operator-overloading binary-operators


【解决方案1】:

你有一个双重Into 间接,可能是错误的。由于您的类型已经实现了AddAssign&lt;T&gt; where T: Into&lt;u64&gt;,因此无需将.into() 添加到您的右手成员。应该预期add_assign(您的示例中未提供)的实现将在下面调用into

seq += rhs;

事实上,添加它只会带来歧义,因为编译器被告知要在类型 X 上调用 Into&lt;X&gt;::into(rhs),而该类型从未在任何地方提及或限制。唯一的约束是Into&lt;u64&gt;,但有多种类型可以满足它。

一个完整的例子:

use std::ops::AddAssign;

struct Sequence;

impl<T: Into<u64>> AddAssign<T> for Sequence {
    fn add_assign(&mut self, rhs: T) {
        let value: u64 = rhs.into();
        // use value
    }
}

fn main() {
    let mut x = Sequence;
    x += 6_u32;
}

将这种类型信息提供给编译器需要的 .into 的语法是什么(如果可能)?

同样,这不是必需的。但是使用所谓的fully qualified syntax 是可能的。

另见:

【讨论】:

  • 哇,现在我觉得自己很笨。是的,只是省略了.into 作品。在其他新闻中,您比cargo check 更擅长于此。
  • 我将此作为改进提交:github.com/rust-lang/rust/issues/89204
  • @EvanCarroll 我很确定错误消息没问题,在其他情况下您可以使用多个intos,我以为您一开始就想像那样使用它^ ^ ,请注意Into 的实现是不可传递的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 2021-09-20
  • 1970-01-01
  • 2014-12-27
  • 1970-01-01
  • 2018-05-07
相关资源
最近更新 更多