简体   繁体   中英

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

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.

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>() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM