我想为自定义结构实现 DeRef
特征,并返回一个 &String
。这是代码块
use std::ops;
use std::path::Path;
fn main() {
println! ("hello world");
}
struct MyDir {
path: String,
}
impl ops::Deref for MyDir {
type Target = String;
fn deref(&self) -> &String {
let txt = format! ("Dir[path = {}]", self.path);
&txt
}
}
编译器诊断:无法返回对局部变量“txt”的引用。返回对当前函数拥有的数据的引用。
我在stackoverflow上查了一些答案,例如( Is there any way to return a reference to a variable created in a function? ),他们都说你不能返回对函数拥有的变量的引用,但后来我在 std 中看到了一段代码片段::路径::路径
[stable(feature = "rust1", since = "1.0.0")]
impl ops::Deref for PathBuf {
type Target = Path;
#[inline]
fn deref(&self) -> &Path {
Path::new(&self.inner)
}
}
为什么它可以返回这里函数持有的引用?
如果有人能提供帮助,我将不胜感激。
最佳答案
Why can it return a reference held by the function here?
因为路径
是a transparent wrapper around an OsStr
也就是说,在运行时它们是完全相同的东西。因此,我们可以从 PathBuf
中获取 OsStr
并重新解释它。从安全角度来看,只要两者完美对齐,就与从内部类型返回普通引用相同。
关于rust - 如何在函数中返回自定义字符串引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77464317/