Saddle Point
Saddle Point

Reputation: 3225

How to store a field that only take reference to String created in `::new()`?

In the below code, how should I store a B field in A? Supposed that I can not change the definition of B.

As a newbie to Rust, I searched Google and most of them explain why the error happens. I could understand the compile error, but I can't figure out how to fix it. Or is it bad design to store the field in this case? Are there other solutions to this?

Thanks!

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() {}

Upvotes: 2

Views: 88

Answers (1)

Netwave
Netwave

Reputation: 42786

Well, in this case you need something to own the data. So just make your A to own it, and then have a method that creates the B type from A:

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

Upvotes: 3

Related Questions