在try 在 struct 之间移动borrow 的数据时,我遇到了生命周期问题.在更高的层面上,我想做一些类似的事情:
- 将YML文件读入字符串缓冲区
- 使用
from_str
将其反序列化为 struct - 使用相同的borrow 数据创建不同的 struct
- 将其写到一个文件中
下面是我构建的一个示例实现,它提供了生存期错误:
use serde::{Serialize, Deserialize};
#[derive(Deserialize, Debug, Serialize)]
pub struct Foo<'a> {
name: &'a str
}
impl<'a> Foo<'a> {
pub fn new(name: &'a str) -> Self {
Self { name }
}
}
#[derive(Deserialize, Debug, Serialize)]
pub struct Bar<'a> {
name: &'a str
}
impl<'a> Bar<'a> {
pub fn new(name: &'a str) -> Self {
Self { name }
}
}
pub trait Visitor {
type Value;
fn visit_table_borrowed<'a>(&mut self, t: &'a Foo<'a>) {
let _ = t;
}
}
pub trait DataBorrowed {
fn accept<V: Visitor>(&self, visitor: &mut V);
}
impl<'a> DataBorrowed for Foo<'a> {
fn accept<V: Visitor>(&self, visitor: &mut V) {
visitor.visit_table_borrowed(self)
}
}
impl<'a> Visitor for Bar<'a> {
type Value = Bar<'a>;
fn visit_table_borrowed(&mut self, t: &'a Foo<'a>) {
self.name = t.name;
}
}
impl<'a> From<Foo<'a>> for Bar<'a> {
fn from(dt: Foo<'a>) -> Self {
let mut table = Bar::new("bar");
dt.accept(&mut table);
table
}
}
fn main() {
let f = Foo::new("foo");
let b: Bar = Bar::from(f);
}
错误:
error[E0308]: method not compatible with trait
--> src/main.rs:49:5
|
49 | fn visit_table_borrowed(&mut self, t: &'a Foo<'a>) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch
|
= note: expected signature `fn(&mut Bar<'a>, &'a Foo<'a>)`
found signature `fn(&mut Bar<'a>, &'a Foo<'a>)`
note: the lifetime `'a` as defined here...
--> src/main.rs:49:5
|
49 | fn visit_table_borrowed(&mut self, t: &'a Foo<'a>) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...does not necessarily outlive the lifetime `'a` as defined here
--> src/main.rs:47:6
|
47 | impl<'a> Visitor for Bar<'a> {
| ^^
For more information about this error, try `rustc --explain E0308`.