在下面的代码中,我应该如何将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 }
}
}
关于rust - 如何存储仅引用 `::new()` 中创建的字符串的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70514945/