O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

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

String slices

The str type is of a fixed size and its contents cannot be changed. Values of this type are typically used as borrowed types (&str) in one of these three ways:

  • Pointing to a statically allocated string (&'static str)
  • As arguments to a function
  • As a view to a string inside another data structure

Let's see how each of these look in code. First, here are two types of statically allocated strings, one in the global scope and one in the function scope:

// string-slices.rs const CONSTANT_STRING: &'static str = "This is a constant string"; fn main() {     let another_string = "This string is local to the main function";     println!("Constant string says: {}", CONSTANT_STRING);     println!("Another string says: {}", another_string); }  ...

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