[Rust] Is it possible to return a reference to a string modified within a function?

고승우·2023년 10월 8일
0

Rust

목록 보기
7/16

It's impossible. It's fundamental question for rustacean, but I attempted various approaches to solve this. As you may be aware, returning the value which created within function can't be live long enough to be returned.

Something I tried

pub struct Person{
    name: String,
    age: i32,
}

fn make_nickname<'a>(person: &'a Person) -> &'a str{
    &format!("goat_{}", person.name) // cannot return reference to temporary value
}

Compiler raise error. String value was created inside the function, and it's lifetime is limited to that function's scope. To work around this issue, we might consider borrowing a string with a longer lifetime and returning a modified value. As String is a mutable it can't make it. Since Vec<u8> is mutable, Alternatvie solution is to use a Vec<u8> instead.

use std::str;

fn extend_string<'a>(buffer: &mut Vec<u8>, string: String) -> &Vec<u8>{
    buffer.extend::<Vec<u8>>(string.into());
    buffer
}

fn main() {
    let mut buffer:Vec<u8> = String::from("value ").into();
    let additional_string = String::from("additional value");
    let result = str::from_utf8(extend_string(&mut buffer, additional_string)).unwrap();
    println!("{}", result);
}

I attempted to convert String into a vector, extend the vector within the function. As a result, I was able to create &str value within the function.

Conclusion

This process is not "returning the string literal which created within the function", but it accomplishes the same goal. Rust imposes strict rules, but we can achieve our desired result!

profile
٩( ᐛ )و 

0개의 댓글