【发布时间】:2016-12-21 13:40:43
【问题描述】:
根据我对生命周期的理解,如果函数的调用者在参数上指定了生命周期,我可以返回具有该生命周期的类型。
这有效,即使有省略:
pub fn substr(s: &str) -> &str {
&s[0..1]
}
pub fn substr_ex<'a>(s: &'a str) -> &'a str {
&s[0..1]
}
但这不是:
use std::fmt::Arguments;
pub fn as_format_arg<'a, T: 'a + ?Sized + Debug>(t: &'a T) -> Arguments<'a> {
format_args!("{:?}", t)
}
error: borrowed value does not live long enough
--> <anon>:16:18
|
16 | format_args!("{:?}", t)
| ^^^^^^ does not live long enough
17 | }
| - temporary value only lives until here
|
= note: borrowed value must be valid for the lifetime 'a as defined on unknown free region bounded by scope CodeExtent(38/CallSiteScope { fn_id: NodeId(42), body_id: NodeId(92) })...
error: `t` does not live long enough
--> <anon>:16:26
|
16 | format_args!("{:?}", t)
| ^ does not live long enough
17 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the lifetime 'a as defined on unknown free region bounded by scope CodeExtent(38/CallSiteScope { fn_id: NodeId(42), body_id: NodeId(92) })...
这是一个错误吗?还是我误解了生命周期?
游戏围栏:https://play.rust-lang.org/?gist=5a7cb4c917b38e012f20c771893f8b3b&version=nightly
【问题讨论】:
-
您的前两个示例返回一个引用,因此它们与最后一个返回拥有对象的示例没有真正可比性。
-
有谁知道现在是否有任何解决方案或替代方案?