4

Have a question: does the slice have any extra data for example zero at the end of the string or size of the string at the beginning of the string?

In this code:

use std::collections::HashMap;

fn main()
{
  let mut hashmap : HashMap< &'static str, &'static str > = HashMap::new();
  hashmap.insert( "EUR", "Euro" );
  hashmap.insert( "USD", "US Dollar" );
  hashmap.insert( "CHF", "Swiss Francs" );

  let usd = hashmap.get( "EUR" );
  if let Some( usd ) = usd
  {
    println!( "usd : {}", usd );
  }
  // < usd : US Dollar
}

Key as well as the value of the HashMap let mut hashmap : HashMap< &'static str, &'static str > could have any length. Right? I don't understand how does the program knows US Dollar has length/size of 9? Does the slice have any extra data for example zero at the end of the string or size of the string at the beginning of the string?

Playground is here.

Kos
  • 1,547
  • 14
  • 23

1 Answers1

5

When a Rust reference points to a DST (Dynamically Sized Type), the reference contains, along with a pointer to the beginning of the data, the length of said data. In this case a string like "hello" is of type &'static str, and because str is unsized:

use std::mem::size_of;
assert_eq!(size_of::<&str>(), 2 * size_of::<usize>());

One usize for the pointer itself and another for the length. str representation on the documentation explains how a &str is a slice containing valid UTF-8 (slices are also unsized so the reference carries the length).

Lonami
  • 5,945
  • 2
  • 20
  • 38