我想为定制 struct 实现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
}
}
编译器诊断:cannot return reference to local variable 'txt'. returns a reference to data owned by the current function.
我查看了一些关于堆栈溢出的答案,例如(Is there any way to return a reference to a variable created in a function?),他们都说不能返回对函数拥有的变量的引用,但后来我在std::path::Path
中看到了一段代码片段
[stable(feature = "rust1", since = "1.0.0")]
impl ops::Deref for PathBuf {
type Target = Path;
#[inline]
fn deref(&self) -> &Path {
Path::new(&self.inner)
}
}
为什么它可以在这里返回函数持有的引用?
如果有人能帮上忙,我将不胜感激.