我在使用结构的生命周期参数时遇到问题.我不是100%肯定如何描述问题,但我创建了一个显示我的编译时错误的简单案例.
struct Ref;
struct Container<'a> {
r : &'a Ref
}
struct ContainerB<'a> {
c : Container<'a>
}
trait ToC {
fn to_c<'a>(&self, r : &'a Ref) -> Container<'a>;
}
impl<'a> ToC for ContainerB<'a> {
fn to_c(&self, r : &'a Ref) -> Container<'a> {
self.c
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是
test.rs:16:3: 18:4 error: method `to_c` has an incompatible type for trait: expected concrete lifetime, but found bound lifetime parameter 'a
test.rs:16 fn to_c(&self, r : &'a Ref) -> Container<'a> {
test.rs:17 self.c …
Run Code Online (Sandbox Code Playgroud) 我有这段代码:
#[derive(Debug)]
struct Foo<'a> {
x: &'a i32,
}
impl<'a> Foo<'a> {
fn set(&mut self, r: &'a i32) {
self.x = r;
}
}
fn main() {
let v = 5;
let w = 7;
let mut f = Foo { x: &v };
println!("f is {:?}", f);
f.set(&w);
println!("now f is {:?}", f);
}
Run Code Online (Sandbox Code Playgroud)
我的理解是,在第一次借用值时v
,'a
struct声明中的泛型生命周期参数将填充值的生命周期v
.这意味着生成的Foo
对象的'a
寿命不得超过此生命周期,或者v
必须至少与Foo
对象一样长.
在对方法的调用中set
,impl
使用块上的生命周期参数,并在方法签名中w
填充值的生命周期'a …
假设我想创建一些包含其他泛型类型的类型,如下所示:
struct MyWrapper<T> {
pub inner: T,
}
Run Code Online (Sandbox Code Playgroud)
现在我希望我的类型有一个方法,如果内部类型满足特定的绑定.例如:我想打印它(在这个例子中没有使用fmt
特征来简化).为此,我有两种可能性:向impl
方法本身添加绑定.
impl<T> MyWrapper<T> {
pub fn print_inner(&self) where T: std::fmt::Display {
println!("[[ {} ]]", self.inner);
}
}
Run Code Online (Sandbox Code Playgroud)
当MyWrapper<()>
我得到一个调用此函数时:
error[E0277]: `()` doesn't implement `std::fmt::Display`
--> src/main.rs:20:7
|
20 | w.print_inner();
| ^^^^^^^^^^^ `()` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
|
= help: the trait `std::fmt::Display` is not implemented for `()`
Run Code Online (Sandbox Code Playgroud)
impl<T: std::fmt::Display> …
Run Code Online (Sandbox Code Playgroud)