【发布时间】:2018-01-15 12:25:19
【问题描述】:
我遇到了一个奇怪的类型推理问题,让我有点摸不着头脑。
我正在为多种类型的结构实现通用特征。我从&str开始:
struct Bar<'a> {
baz: &'a str,
}
trait Foo<T> {
fn foo(&self) -> T;
}
impl<'a> Foo<&'a str> for Bar<'a> {
fn foo(&self) -> &'a str {
self.baz
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_str_a() {
let bar = Bar { baz: "asd" };
assert_eq!("asd", bar.foo());
}
}
这行得通——当我为 u8 类型添加另一个实现时,问题就来了:
struct Bar<'a> {
baz: &'a str,
}
trait Foo<T> {
fn foo(&self) -> T;
}
impl<'a> Foo<&'a str> for Bar<'a> {
fn foo(&self) -> &'a str {
self.baz
}
}
impl<'a> Foo<u8> for Bar<'a> {
fn foo(&self) -> u8 {
8
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_str_a() {
let bar = Bar { baz: "asd" };
assert_eq!("asd", bar.foo());
}
#[test]
fn test_u8() {
let bar = Bar { baz: "asd" };
assert_eq!(8 as u8, bar.foo());
}
}
在这种情况下,我收到以下错误:
error[E0283]: type annotations required: cannot resolve `Bar<'_>: Foo<_>`
--> src/main.rs:28:31
|
28 | assert_eq!("asd", bar.foo());
| ^^^
如果我将值存储在变量中,它会起作用:
let foo: &str = bar.foo();
在我的生产代码中,我做了很多断言,这会使事情变得有点混乱。我也尝试过bar.foo() as &str,但这也失败了,因为编译器也不知道bar.foo() 的类型。我正在尝试为编译器找到一种简洁的方式来了解类型。
【问题讨论】:
标签: generics types casting rust traits