rust - Return local String as a slice (&str) -


there several questions seem same problem i'm having. example see here , here. i'm trying build string in local function, return &str. slicing isn't working because lifetime short. can't use str directly in function because need build dynamically. however, i'd prefer not return string since nature of object going static once it's built. there way have cake , eat too?

here's minimal non-compiling reproduction:

fn return_str<'a>() -> &'a str {     let mut string = "".to_string();      in 0..10 {         string.push_str("actg");     }      &string[..] } 

no, cannot it. there @ least 2 explanations why so.

first, remember references borrowed, i.e. point data not own it, owned else. in particular case string, slice want return, owned function because stored in local variable.

when function exits, local variables destroyed; involves calling destructors, , destructor of string frees memory used string. however, want return borrowed reference pointing data allocated string. means returned reference becomes dangling - points invalid memory!

rust created, among else, prevent such problems. therefore, in rust impossible return reference pointing local variables of function, possible in languages c.

there explanation, more formal. let's @ function signature:

fn return_str<'a>() -> &'a str 

remember lifetime , generic parameters are, well, parameters: set caller of function. example, other function may call this:

let s: &'static str = return_str(); 

this requires 'a 'static, of course impossible - function not return reference static memory, returns reference strictly lesser lifetime. such function definition unsound , prohibited compiler.

anyway, in such situations need return value of owned type, in particular case owned string:

fn return_str() -> string {     let mut string = string::new();      _ in 0..10 {         string.push_str("actg");     }      string } 

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -