【发布时间】:2015-09-03 03:23:32
【问题描述】:
我刚刚在我的一些代码中遇到了一个问题,并设法将其精简为以下最小示例:
use std::iter::IntoIterator;
use std::marker::PhantomData;
trait Bar<'a> {
fn compile_plz(&self) -> &'a str;
}
struct Foo<'a> {
ph: PhantomData<&'a str>
}
impl<'a> Bar<'a> for Foo<'a> {
fn compile_plz(&self) -> &'a str {
"thx"
}
}
fn do_something_with_bars<'a, I>(it: I) -> Result<(), ()> where I: IntoIterator<Item=&'a Bar<'a>> {
Ok(())
}
fn take_bar<'a, B>(b: &'a B) where B: Bar<'a> {
do_something_with_bars(vec![b]);
}
fn main() {
let f = Foo{ph: PhantomData};
take_bar(&f);
}
这会失败并出现以下错误:
23:5: 23:27 错误:类型不匹配解析
<collections::vec::Vec<&B> as core::iter::IntoIterator>::Item == &Bar<'_>: 预期的类型参数, 找到特质栏 [E0271]
但是,将 vec![b] 更改为 vec![b as &Bar] 可以正常工作。但既然b 是&B 类型,而B 有一个Bar<'a> 界限,为什么编译器不能确定b 确实是一个&Bar?
【问题讨论】:
标签: rust