返回对一个结构体部分的引用作为另一个结构体的字段[重复]

2024-02-26

如果可能的话,我希望将一个结构移动到另一个结构中,并获取第一个结构的部分作为其他结构的部分的引用,而无需克隆或复制。如何以正确的方式去做?

fn main() {
    let foo = Foo::new();
    let bar = Bar::new(foo);
    println!("{:?}", bar);
}

#[derive(Debug)]
struct Foo {
    v: String,
}

impl Foo {
    pub fn new() -> Self {
        Foo {
            v: String::from("a|b"),
        }
    }

    pub fn get_a(&self) -> &str {
        &self.v[0..1]
    }

    pub fn get_b(&self) -> &str {
        &self.v[2..3]
    }
}

#[derive(Debug)]
struct Bar<'a> {
    foo: Foo,
    a: &'a str,
    b: &'a str,
}

impl<'a> Bar<'a> {
    pub fn new(f: Foo) -> Self {
        Bar::parse(f)
    }

    fn parse(f: Foo) -> Self {
        let a = f.get_a();
        let b = f.get_b();

        Bar { foo: f, a, b }
    }
}

我收到一个错误:

error[E0515]: cannot return value referencing function parameter `f`
  --> src/main.rs:44:9
   |
41 |         let a = f.get_a();
   |                 - `f` is borrowed here
...
44 |         Bar { foo: f, a, b }
   |         ^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function

error[E0515]: cannot return value referencing function parameter `f`
  --> src/main.rs:44:9
   |
42 |         let b = f.get_b();
   |                 - `f` is borrowed here
43 | 
44 |         Bar { foo: f, a, b }
   |         ^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function

error[E0505]: cannot move out of `f` because it is borrowed
  --> src/main.rs:44:20
   |
35 | impl<'a> Bar<'a> {
   |      -- lifetime `'a` defined here
...
41 |         let a = f.get_a();
   |                 - borrow of `f` occurs here
...
44 |         Bar { foo: f, a, b }
   |         -----------^--------
   |         |          |
   |         |          move out of `f` occurs here
   |         returning this value requires that `f` is borrowed for `'a`

论证的生命周期f to parse结束时parse返回。较旧的 Rust 编译器版本返回了一条可能更有用的错误消息:

error[E0597]: `f` does not live long enough
  --> t.rs:41:17
   |
41 |         let a = f.get_a();
   |                 ^ borrowed value does not live long enough
...
45 |     }
   |     - borrowed value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the impl at 35:1...
  --> t.rs:35:1
   |
35 | / impl<'a> Bar<'a> {
36 | |     pub fn new(f: Foo) -> Self {
37 | |         Bar::parse(f)
38 | |     }
...  |
45 | |     }
46 | | }
   | |_^

我可以通过更改定义来编译你的示例Bar to:

#[derive(Debug)]
struct Bar<'a> {
    foo: &'a Foo,
    a: &'a str,
    b: &'a str,
}

并传递类型的引用&'a Foo to Bar::new and Bar::parse。但是,尚不清楚该解决方案是否适用于您原来的问题。也许你需要使用Rc如果股权结构过于复杂。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

返回对一个结构体部分的引用作为另一个结构体的字段[重复] 的相关文章

随机推荐