Strings

The way Rust works with strings differs a bit from strings in other languages. All strings are valid sequences of Unicode (UTF8) bytes. They can contain null bytes, but they are not null terminated as in C.

Rust distinguishes two types of string:

  • The strings we have used until now are string slices, whose type is &str. The & points out that a string slice is a reference to a string. They are immutable and have a fixed size. For example, the following bindings declare string slices:
    // from Chapter 4/code/strings.rs 
    let magician1 = "Merlin"; 
    let greeting = "Hello, world!"; 
  • Or if we explicitly annotate the string variable with its type:
    let magician2: &str = "Gandalf"; 
  • We can also define it as a string literal:
 let magician2: ...

Get Rust Essentials - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.