rust - 如何在函数中返回自定义字符串引用?

标签 rust

我想为自定义结构实现 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/

相关文章:

vector - 如何匹配迭代器的项目?

unit-testing - 将特定测试编译成二进制文件

rust - 在 and_then 的类型定义中, T 从哪里来?

rust - 获取分区函数中项目的索引

rust - 如何将没有yield的闭包转换为生成器?

function - 如何编写一个接受函数片段的函数?

rust - 在 Rust 中创建一个 HashMap<i32, i32>

rust - "borrowed value does not live long enough"好像怪错了

rust - 匹配错误结果并在分配变量时退出程序

rust - `&mut retval` 和 `retval as *const T as *mut T` 和有什么区别?