What are the differences between them?
str
is the type to store texts in a more crude way. Remember a little the array of char
C, because he’s a array of bytes (a character can be formed by more than 1 byte). But it’s different mainly because it uses a UTF-8 format and not ASCII, and of course, it manages to catch the size in constant time. And also because it’s immutable.
It’s a type by value, so the text is already the object. It is usually used by reference not to have to copy from one context to another, and in some rare cases ends up being allocated in the heap, when you need it, you have the solution to String
.
A text literal is of the type &'static str
this means that it will be a reference to the raw object elsewhere. And that place is static memory, but that 'static
does not indicate place, but life time. It is a way of saying that this object will last for all has can application life. Rust’s great balcony is absolute control of life time without a garbage collector, so you need to tell life time in much of the situations.
String
is a wrapper to the str
and is a reference type allocated in the heap, therefore life time tends to be longer and requires less sophisticated control by the programmer.
In addition it is changeable, so it can change the data without having to copy to another object, and the change management is all internal, instead of being a array and bytes is a list of characters (so even the size can change).
His lifespan is tied to having reference to it, so in a way we can say that it’s managed by a form of Garbage Collector.
The collection is made when the reference to the object ceases to exist. The type String
has a property reference, so there’s a direct link between them.
The class is very complete: documentation.
fn main() {
let strVar : &'static str = "str";
let stringVar : String = "String".to_string(); // precisa converter o tipo
teste(strVar);
teste(&stringVar);
}
fn teste(texto: &str) {
println!("Isto é um {}", texto);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
When to use str and when to use String?
The preference is to use str
whenever possible because immutable is better, and if you have easy control of life time fits with the philosophy of language saving resources. If you need the changeability or leave life freer and controlled by circumstances, then the String
is preferable. It is less efficient in general use, but of course it will be more efficient than copying the object str
to there is to here for one reason or another.
Don’t forget to study slice
.
Why create such a distinction?
Languages that seek efficiency need to give the most efficient and the most flexible and powerful option. Languages of script is that they choose only the flexible to be easier.