design-patterns - 在 Rust 中,当您需要一个引用保持结构有时拥有其引用的数据时,该模式是什么?

标签 design-patterns rust borrow-checker

考虑以下数据结构:

struct ReferenceHoldingStruct<'a> {
    pub prop: &'a str
}
这种模式通常很有用,特别是在解析器(我的用例)中,用于“给”一个结构一些字符串数据而不重新分配它:
fn generate_these_1<'a>(input: &'a str) -> ReferenceHoldingStruct<'a> {
    ReferenceHoldingStruct { prop: input }
}
但是,我有一个例子,我有一个像上面这样的结构,但在一个地方我需要生成“独立”的实例;即他们拥有自己的数据:
fn generate_these_2<'a>(input: String) -> ReferenceHoldingStruct<'a> {
    ReferenceHoldingStruct { prop: input.as_str() }
}
我理解为什么这个版本不起作用:被引用的字符串并不存在于 Rust 可以看到它会徘徊以继续履行结构的 &str 的任何地方。引用。我想也许这会奏效:
fn generate_these_2<'a>(input: String) -> (String, ReferenceHoldingStruct<'a>) {
    (input, ReferenceHoldingStruct { prop: input.as_str() })
}
因为至少字符串不会立即被删除。我想也许 Rust 可以弄清楚这个元组既包含引用又包含它引用的数据,因此只要它们像这样保持在一起,它们就是有效的。但是没有骰子:这仍然不起作用。它将引用视为借用,将向元组的移动视为移动,您不能“同时”执行这两项操作。
所以,我理解这个问题,但不知道从哪里开始。这种情况的标准做法是什么?

最佳答案

这是 Cow 的示例(在评论中提到):

use std::borrow::Cow;

struct ReferenceHoldingStruct<'a> {
    pub prop: Cow<'a, str>
}

fn generate_these_1<'a>(input: &'a str) -> ReferenceHoldingStruct<'a> {
    ReferenceHoldingStruct { prop: Cow::Borrowed(input) }
}

fn generate_these_2<'a>(input: String) -> ReferenceHoldingStruct<'a> {
    ReferenceHoldingStruct { prop: Cow::Owned(input) }
}

关于design-patterns - 在 Rust 中,当您需要一个引用保持结构有时拥有其引用的数据时,该模式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65031642/

相关文章:

arrays - 如何将切片转换为数组引用?

rust - 为什么不编译 - 使用未声明的类型名称 `thread::scoped`

loops - 在循环的前一次迭代中多次借用

design-patterns - CQRS 和命令去抖动

sql - 替换动态文本 SQL

.net - .Net 中的单例模式是不可能的吗?

python - Sed 删除/替换双括号

compiler-errors - Rust 借用编译错误

rust - nom 解析器借用检查器问题

rust - 借用检查器不允许从树遍历函数返回可变引用