rust - 如何存储仅引用 `::new()` 中创建的字符串的字段?

标签 rust reference lifetime

在下面的代码中,我应该如何将B字段存储在A中?假设我无法更改 definition of B .

作为 Rust 的新手,我搜索了 Google,其中大多数都解释了错误发生的原因。我可以理解编译错误,但我不知道如何修复它。或者在这种情况下存储该字段是不是设计不好?还有其他解决方案吗?

谢谢!

use std::io::Read;

struct A<'a> {
    b: B<'a>,
}

impl<'a> A<'a> {
    pub fn new(mut reader: impl Read) -> Self {
        let mut s = String::new();
        reader.read_to_string(&mut s);

        let b = B { b: &s };
        A { b }
    }
}

// From 3rd party library, can't change the struct!
struct B<'a> {
    b: &'a str,
}

fn main() {}

最佳答案

好吧,在这种情况下,您需要一些东西来拥有数据。因此,只需让您的 A 拥有它,然后使用一个方法从 A 创建 B 类型即可:

struct A {
    s: String,
}

// From 3rd party library, can't change the struct!
struct B<'a> {
    b: &'a str,
}

impl A {
    pub fn new(mut reader: impl Read) -> Self {
        let mut s = String::new();
        reader.read_to_string(&mut s);

        A { s }
    }

    fn as_b(&self) -> B {
        B { b: &self.s }
    }
}

Playground

关于rust - 如何存储仅引用 `::new()` 中创建的字符串的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70514945/

相关文章:

Rust 指定局部变量的生命周期

multithreading - 如何等待 tokio 任务完成?

rust - Rust 签名中的 'a 用于什么?

rust - 如何在稳定的Rust中不占用堆栈空间的情况下在堆上分配结构?

c++ - 实现树结构最安全的方法是什么?

php - 是否已弃用通过引用传递变量?

javascript - javascript中引用和实例之间的区别

rust - "The parameter type ` C ` may not live long enough", 不需要的时候

rust - 有什么方法可以递归地展平元组吗?

使用 nom 解析驼峰式字符串