O'Reilly logo

Rust Essentials - Second Edition by Ivo Balbaert

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required