Dev Overflow Logo

Dev Overflow

Global search

Search across questions, answers, users and tags.

Loading...
save

Rust: what is the actual difference between String and &str?

clock icon

asked 2 months ago

message icon

2

eye icon

1.9K

Coming from garbage-collected languages, having two string types is the thing I keep tripping over. When does a function take one versus the other?

2 Answers

String owns heap-allocated bytes and can grow. &str is a borrowed view into bytes someone else owns — a pointer and a length, no allocation.

For parameters, the rule is nearly always: take &str.

1fn greet(name: &str) -> String {
2 format!("Hello, {name}!")
3}
1fn greet(name: &str) -> String {
2 format!("Hello, {name}!")
3}

A caller with a String can pass &s and deref coercion handles it, while a caller with a literal passes it directly. Taking String forces every caller to allocate or give up ownership for no reason.

Return String when you are producing new text, as above. Return &str only when it borrows from an input, and the lifetimes will say so.

The mental shortcut that made it click for me: String is to &str what Vec<T> is to &[T]. Same owned/borrowed split, same "take the borrowed form in arguments" advice.

1

of 1

Write your answer here

Introduce the problem and expand on what you've put in the title.

Top Questions