基於我對生命週期的理解,如果函數的調用者指定了參數的生命週期,我可以返回具有該生命週期的類型。爲什麼我不能從'T'返回fmt ::參數<'a>?
這工作,即使有省音:
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
你的前兩個例子返回一個引用,所以它們與返回擁有對象的最後一個沒有真正的可比性。 – ljedrz