rust - How does the lifetime work on constant strings? -
i read tutorial on official website , have questions on lifetime of constant strings.
i error when write following code:
fn get_str() -> &str { "hello world" }
error:
test.rs:1:17: 1:21 error: missing lifetime specifier [e0106] test.rs:1 fn get_str() -> &str { ^~~~ test.rs:1:17: 1:21 help: run `rustc --explain e0106` see detailed explanation test.rs:1:17: 1:21 help: function's return type contains borrowed value, there no value borrowed test.rs:1:17: 1:21 help: consider giving 'static lifetime error: aborting due previous error
however it's ok when add parameter:
fn get_str(s: &str) -> &str { "hello world" }
why work? how "hello world"
borrow parameter s
, though has nothing 's'?
lifetime elision infers full type of
fn get_str(s: &str) -> &str
is
fn get_str<'a>(s: &'a str) -> &'a str
which means return value of get_str
has valid long s
valid. actual type of string constant "hello world"
&'static str
, means valid entire run of program. since satisfies lifetime constraints in function signature (because 'static
includes 'a
'a
), works.
however, more sensible way original code work add explicit lifetime function type:
fn get_str() -> &'static str { "hello world" }
how "hello world" borrow parameter 's', has nothing 's'?
there 2 options make sense return value's lifetime in function single reference argument:
- it can
'static
, should in example, or - the return value's lifetime has tied lifetime of argument, lifetime elision defaults to.
there rationale choosing latter in link @ top of post, comes down fact latter far more common case. note lifetime elision does not @ function body @ all, goes function signature. that's why won't take fact you're returning string constant account.
Comments
Post a Comment