【问题标题】:Why is std::borrow::Borrow not implementet for every Type?为什么没有为每个类型实现 std::borrow::Borrow?
【发布时间】:2019-11-03 06:52:45
【问题描述】:

在文档中指出

impl<T> Borrow<T> for T where
    T: ?Sized, 

我会读这个:

这个 Trait 对每个类型都实现了,即使是没有大小的类型。

这对吗?

我收到错误消息: std::borrow::Borrow&lt;T&gt; 的 trait 没有为 &amp;num_complex::Complex&lt;f64&gt; 实现

我无法理解。

(我不想发布整个代码,我只是想澄清一下哪些类型实现了 std::borror::Borrow)

【问题讨论】:

  • 你在哪里找到impl&lt;T&gt; Borrow&lt;T&gt; for T where T: ?Sized,在我看来impl&lt;T&gt; Borrow&lt;T&gt; for &amp;T where T: ?Sized 是正确的。但这并不能解释您的错误消息,也许您应该透露更多代码。

标签: rust traits


【解决方案1】:

要认识到的重要一点是,在毯子impl 中只有一个T,并且它必须在两个地方都代表相同的类型:

impl<T> Borrow<T> for T
    where T: ?Sized

实现每种类型T,只有特定的特征Borrow&lt;T&gt;i64 实现Borrow&lt;i64&gt;String 实现Borrow&lt;String&gt; 等。当我们用T = &amp;num_complex::Complex&lt;f64&gt; 实例化它时,实现了什么特征?

impl Borrow<&num_complex::Complex<f64>> for &num_complex::Complex<f64>  // (not compilable code, just illustrative)

换句话说,你可以借用&amp;Complex&lt;f64&gt; as&amp;Complex&lt;f64&gt;,但你不能随意借用T(无论如何,这没有多大意义) .

您在一些通用代码中使用它,其中T 可以是任何东西,因此Borrow&lt;T&gt; for T 的毯子impl 不适用。您可以通过添加特征绑定来解决此问题:

where num_complex::Complex<f64>: Borrow<T>

这意味着Complex&lt;f64&gt;本身实现了Borrow&lt;T&gt;,或者

where for<'a> &'a num_complex::Complex<f64>: Borrow<T>

这意味着对Complex&lt;f64&gt; 的任何引用都会实现Borrow&lt;T&gt;。根据您的实际代码,由于 autoref/autoderef,其中一个或两个可能会起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 2023-01-26
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多