如何在Rust中给参考明确的寿命?
我正在尝试返回 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
带有额外的成员。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这种情况下,您不应返回
&amp; str
,因为底层对象&amp; str
在函数终止时将删除引用。本质上,您正在尝试返回对被删除的临时值的引用。请参阅string之间的差异
和&amp; str
。字符串
可能是您想要的。此编译: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 betweenString
and&str
.String
is probably what you want instead. This compiles: