How much memory (in bytes) is allocated to `&'static str` in Rust?

Viewed 65

In this example:


enum BinaryTree<T> { 
       Empty,
       NonEmpty(Box<TreeNode<T>>),
}
fn binary_tree_size() {
    use std::mem::size_of;

    let word = size_of::<usize>();
 
    type Triple = (&'static str, BinaryTree<&'static str>, BinaryTree<&'static str>);
    assert_eq!(size_of::<Triple>(), 4 * word);
}

I understand that both BinaryTree<&'static str> inside Triple have a size of usize each (because the largest field size of the enum is a Box). So am I correct in inferring that &'static str is of size 2 * usize? I can't find how much memory is allocated to &'static str in the docs.

1 Answers

Every slice consists of 2 components: the pointer to the first byte of the slice and the length of the slice. To represent both pointer and length Rust is using usize. The str type is a slice, thus the size_of::<&str>() == 2 * size_of::<usize>().

Related