寿命についての私の理解に基づいて、関数の呼び出し側がパラメータの有効期間を指定すると、その有効期間のある型を返すことができます。fmt :: Argumentsを返すことができない理由<'a>& 'a T?
これはさえエリジオンと、動作します:
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
最初の2つの例は参照を返します。したがって、実際には所有オブジェクトを返す最後の例と実際には比較できません。 – ljedrz