Lifetime &str vs String

Hello,

I don't understand why the first code compile and the second do not compile.
What is the lifetime of the string slice str2 in the first code? Is it static ? I come from C++ and for me this should push the str on the stack no?

The first code:

fn compile()
{
    let str1 = "abcd"; 
    {    
        let str2 = "xyz"; 
        let result = longest(str1, str2); 
        println!("The longest string is {}", result);
    }
}

The second code:

fn not_compile()
{
    let str1 = "abcd";
    let result;
    {
        let str2 = String::from("xyz");
        result = longest(str1, &str2);
    }
    println!("The longest string is {}", result);
}

Thank you

The str literals like "..." will be references to static data in the binary. That data does not get copied to the stack, just referred in place. This is also true of C and C++ string literals -- their char* points to static data.

The String will be allocated on the heap, and has a non-static lifetime as a result.

5 Likes

I though Rust string literal was the C++ equivalent:

const char str1[4] = { 'a', 'b', 'c', 'd' };
const size_t str1_length = 4;

Which is on the stack and not static.
So the equivalent is more:

const char* str1 = "abcd";
const size_t str1_length = 4;

Is there a way to have a string on the stack in Rust? And have the same as C++ Compiler Explorer?

I don't think there's a direct way to create a str on the stack, but you can create an array of [u8; N] and call str::from_utf8 to reference it.

2 Likes

Ok thank you

There is also the arraystring crate for fixed capacity strings that provide a String-like interface, and smallstr which provides a form of String that dynamically chooses either the stack or the heap based on length.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.