Owned String literal?

Is there a way to create an owned String literal?
Something like: o"my string"


Strings are allocated on the heap and usually Rust requires an explicit operation in the code for that.

let s = o"my string";

is just:

let s = "my string".to_owned();

making explicit that memory will be allocated and data from the string will be copied.

If you just want the syntactic sugar you can go with a macro, like:

let s = o!("my string")

but, IMHO, it isn't a great idea. :slight_smile:

The idiomatic way:

"my string".to_string();

Some people prefer

String::from("my string");
1 Like

@steveklabnik is to_string() the idiomatic way? Nice to know, in a lot of examples and Rust code I always found to_owned().

to_string used to be slower than the alternatives.

It isn't any more, but I still personally prefer String::from or .to_owned because "my string" is clearly already a string; having what looks like it should be a no-op actually change the types involved is just... weird. But that might just be me.


It is, because it's mostly directly stating what you want.

For a while, it was slower to some alternatives, like to_owned, so some people switched over during that time. But that's not true anymore.

GHOST OF RUST PAST: ~"hello" was the original syntax for an owned string literal.

GHOST OF RUST PRESENT: "hello".into() is yet another way to do it, shorter but more ambiguous.

GHOST OF RUST FUTURE: box "hello" may become a valid String expression someday.