在 `assert_eq!()` 中使用 `as_ref()` 时需要输入注释

Type annotation required when using `as_ref()` in `assert_eq!()`

我在我的代码中使用了新的通用转换特征,但体验到人机工程学方面的问题。正如您在示例中看到的那样,有问题的代码实现了 AsRef<str> for [Ascii]

现在我想在 assert_eq!() 中使用 v.as_ref() 并期望 v.as_ref() returns 使用提供的实现 &str 因为第二个参数 assert_eq!() 是类型 &str.

没有 AsRef<String> for [Ascii] 的实现,所以在我看来只有 PartialEq 的一个实现起作用:PartialEq<str> for &str.

编译器不遵循我的解释并抱怨需要类型注释。我怎样才能避免显式注释,为什么编译器不能找出 AsRef<_>?

的正确实现

谢谢

#![feature(convert)]

struct Ascii { chr: u8 }

impl AsRef<str> for [Ascii] {
    fn as_ref(&self) -> &str {
        unsafe { ::std::mem::transmute(self) }
    }
}

fn main() {
    let v = [Ascii { chr: 65 }, Ascii { chr: 66 }];
    assert_eq!(v.as_ref(), "AB");
    // Workaround: explicit type annotation.
    //assert_eq!(AsRef::<str>::as_ref(&v[..]), "AB");
}

围栏link:http://is.gd/ZcdqXZ

<anon>:15:18: 15:26 error: type annotations required:
    cannot resolve `[Ascii] : core::convert::AsRef<_>` [E0283]
<anon>:15     assert_eq!(v.as_ref(), "AB");
                       ^~~~~~~~

更详细地查看文档中的 listed implementors of AsRef,您会发现还有另一个实现在那里发生冲突:impl<T> AsRef<[T]> for [T]。所以它不能决定 v.as_ref() 应该是 &str 还是 &[Ascii].

类型