gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:50:00 25 4
gpt4 key购买 nike

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

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