我想实现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
}
}
Run Code Online (Sandbox Code Playgroud)
编译器诊断:无法返回对局部变量“txt”的引用。返回对当前函数拥有的数据的引用。
我查了stackoverflow上的一些答案,比如(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)
}
}
Run Code Online (Sandbox Code Playgroud)
为什么它可以返回这里函数持有的引用?
如果有人能提供帮助,我将不胜感激。
为什么它可以返回这里函数持有的引用?
因为Path是运行时围绕 aka 的透明包装器,所以它们是OsStr完全相同的东西。所以我们可以从中得到一个OsStr并PathBuf重新解释它。从安全角度来看,只要两者完美对齐,就与从内部类型返回正常引用相同。
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |