如何在Rust中给参考明确的寿命?

发布于 2025-02-10 04:33:18 字数 1266 浏览 1 评论 0 原文

我正在尝试返回 result<(),& str> 在Rust中,其中& str嵌入了有关发生的任何错误的数据。例如,说我有以下代码:

struct Foo {
    pub mynum :i32,
}

impl Foo {
    fn do_something(&self) -> Result<(), &str> {
        if self.mynum % 12 == 0 {
            return Err(&format!("error! mynum is {}", self.mynum))
        }
        Ok(())
    }
}

fn main() {
    let foo_instance = Foo{
        mynum: 36,
    };
    let result = foo_instance.do_something().unwrap();
    println!("{:?}",result)
}

如果我在 Rust Playground ,我得到的

error[E0515]: cannot return value referencing temporary value
 --> src/main.rs:9:20
  |
9 |             return Err(&format!("error! mynum is {}", self.mynum))
  |                    ^^^^^-----------------------------------------^
  |                    |    |
  |                    |    temporary value created here
  |                    returns a value referencing data owned by the current function

是不需要的。 我如何告诉生锈编译器,用lifetime 'a 创建&amp; str ?如果可能的话,我不想使用'static ,也不想加入 foo 带有额外的成员。

I'm trying to return a Result<(), &str> in rust, where the &str has embedded data about any errors which have occurred. For example, say I have the following code:

struct Foo {
    pub mynum :i32,
}

impl Foo {
    fn do_something(&self) -> Result<(), &str> {
        if self.mynum % 12 == 0 {
            return Err(&format!("error! mynum is {}", self.mynum))
        }
        Ok(())
    }
}

fn main() {
    let foo_instance = Foo{
        mynum: 36,
    };
    let result = foo_instance.do_something().unwrap();
    println!("{:?}",result)
}

If I run this in the rust playground, I get

error[E0515]: cannot return value referencing temporary value
 --> src/main.rs:9:20
  |
9 |             return Err(&format!("error! mynum is {}", self.mynum))
  |                    ^^^^^-----------------------------------------^
  |                    |    |
  |                    |    temporary value created here
  |                    returns a value referencing data owned by the current function

which isn't desired.
How do I tell the Rust compiler that to create a &str with lifetime 'a where 'a is the lifetime of self? I don't want to use 'static if possible, and I don't want to load Foo with extra members..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

与君绝 2025-02-17 04:33:18

在这种情况下,您不应返回&amp; str ,因为底层对象&amp; str 在函数终止时将删除引用。本质上,您正在尝试返回对被删除的临时值的引用。请参阅 string之间的差异&amp; str

字符串可能是您想要的。此编译:

fn do_something(&self) -> Result<(), String> {
    if self.mynum % 12 == 0 {
        return Err(format!("error! mynum is {}", self.mynum));
    }
    Ok(())
}

You should not return a &str in this case because the underlying object the &str is referencing gets dropped when the function terminates. Essentially, you are attempting to return a reference to a temporary value which gets deleted. See this article on differences between String and &str.

String is probably what you want instead. This compiles:

fn do_something(&self) -> Result<(), String> {
    if self.mynum % 12 == 0 {
        return Err(format!("error! mynum is {}", self.mynum));
    }
    Ok(())
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文