Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these 3 ways of declaring a string in Rust?

Tags:

let hello1 = "Hello, world!"; let hello2 = "Hello, world!".to_string(); let hello3 = String::from("Hello, world!"); 
like image 876
user Avatar asked May 10 '16 22:05

user


People also ask

What is the difference between STR and string in Rust?

String is the dynamic heap string type, like Vec : use it when you need to own or modify your string data. str is an immutable1 sequence of UTF-8 bytes of dynamic length somewhere in memory. Since the size is unknown, one can only handle it behind a pointer.

Why does Rust have two string types?

Rust doesn't sugar coat a lot of the ugliness and complexity of string handling from developers like other languages do and therefore helps in avoiding critical mistakes in the future. By construction, both string types are valid UTF-8. This ensures there are no misbehaving strings in a program.

What is str type in Rust?

The str type, also called a 'string slice', is the most primitive string type. It is usually seen in its borrowed form, &str . It is also the type of string literals, &'static str . String slices are always valid UTF-8.

How is store the string Rust?

A String is stored as a vector of bytes ( Vec<u8> ), but guaranteed to always be a valid UTF-8 sequence. String is heap allocated, growable and not null terminated. &str is a slice ( &[u8] ) that always points to a valid UTF-8 sequence, and can be used to view into a String , just like &[T] is a view into Vec<T> .


1 Answers

let hello1 = "Hello, world!"; 

This creates a string slice (&str). Specifically, a &'static str, a string slice that lives for the entire duration of the program. No heap memory is allocated; the data for the string lives within the binary of the program itself.

let hello2 = "Hello, world!".to_string(); 

This uses the formatting machinery to format any type that implements Display, creating an owned, allocated string (String). In versions of Rust before 1.9.0 (specifically because of this commit), this is slower than directly converting using String::from. In version 1.9.0 and after, calling .to_string() on a string literal is the same speed as String::from.

let hello3 = String::from("Hello, world!"); 

This converts a string slice to an owned, allocated string (String) in an efficient manner.

let hello4 = "hello, world!".to_owned(); 

The same as String::from.

See also:

  • How to create a String directly?
  • What are the differences between Rust's `String` and `str`?
like image 192
Shepmaster Avatar answered Oct 23 '22 21:10

Shepmaster