gpt4 book ai didi

rust - 如何创建一个构建器,该构建器采用为 `&str` 的切片实现 AsRef 的类型?

转载 作者:行者123 更新时间:2023-11-29 08:27:33 24 4
gpt4 key购买 nike

我正在调用一个接受&[&str] 的函数。由于编写 ["aa", "bb"] 更方便,而不是 &["aa", "bb"],我决定添加 作为引用:

struct Builder<'a> {
s: Option<&'a [&'a str]>,
}

impl<'a> Builder<'a> {
fn new() -> Builder<'a> {
Builder { s: None }
}

fn abc<S>(&mut self, s: S) -> &mut Self
where S: AsRef<[&'a str]> + 'a
{
self.s = Some(s.as_ref());
self
}

fn build(&self) -> u32 {
0
}
}

fn main() {
Builder::new().abc([]).build();
}

( Playground )

但是lifetime有个问题:

error: `s` does not live long enough
self.s = Some(s.as_ref());
^
note: reference must be valid for the lifetime 'a as defined on the block at 12:4...
{
self.s = Some(s.as_ref());
self
}
note: ...but borrowed value is only valid for the scope of parameters for function at 12:4
{
self.s = Some(s.as_ref());
self
}

最佳答案

代码尝试将数组的所有权转移给函数abc([]),引用数组(s.as_ref()),然后它丢弃数组,这会留下一个指向未定义内存的指针。 Rust 不允许你这样做。

I did it: self.s = Some(unsafe { std::mem::transmute(s.as_ref()) });

这是一个非常糟糕的主意。如上所述,您现在拥有对不再存在的数组的引用。该内存允许在未来放置任何东西,访问指针将在最好的情况下导致您的程序崩溃,但也可以继续执行但带有无意义的数据。

只有在了解所有后果后才使用不安全代码。

关于rust - 如何创建一个构建器,该构建器采用为 `&str` 的切片实现 AsRef 的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38015498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com