Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can size_of be used on unsized types?

Tags:

memory

rust

The documentation for std::mem::size_of doesn't provide an example of &str or String being used, but both return sizes with the following code:

println!("The size of a string slice (&str): {}", mem::size_of::<&str>());
// OUTPUT: The size of a string slice (&str): 16
println!("The size of a growable string (String): {}", mem::size_of::<String>());
// OUTPUT: The size of a growable string (String): 24

From my understanding, a &str type is just a reference to the beginning of a "sequence of Unicode scalar values encoded as a stream of UTF-8 bytes". Is &str referring to the size of two pointers? I know a pointer is 8 bytes long on a 64-bit system.

mem::size_of::<str>() does return an error, like I would have expected. However, both String and &String return sizes.

like image 497
Duncan Avatar asked Aug 03 '18 14:08

Duncan


People also ask

Why do we use sizeof?

Sizeof is a much used operator in the C or C++. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t.

What is sizeof data type?

sizeof is a unary operator in the programming languages C and C++. It generates the storage size of an expression or a data type, measured in the number of char-sized units. Consequently, the construct sizeof (char) is guaranteed to be 1.

Why do we use sizeof in C?

What is the sizeof() function in C? The sizeof() function in C is a built-in function that is used to calculate the size (in bytes)that a data type occupies in ​the computer's memory.

Why sizeof operator is used in C++?

The sizeof is a keyword, but it is a compile-time operator that determines the size, in bytes, of a variable or data type. The sizeof operator can be used to get the size of classes, structures, unions and any other user defined data type.


1 Answers

Why can size_of be used on unsized types?

It cannot. If it could, it would be defined as:

pub const fn size_of<T: ?Sized>() -> usize
//                    ^^^^^^^^

Why can size_of be used on [&str / String / &String]?

&str, String, and &String are all sized types.

A &str is essentially:

struct StringSlice {
    ptr: *const u8,
    len: usize,
}

A String is essentially:

struct String {
    ptr: *const u8,
    len: usize,
    cap: usize,
}

A &String is essentially:

struct StringRef {
    ptr: *const String,
}

referring to the size of two pointers

A usize is an integer type that is guaranteed to be the size of a native pointer, so... kind of?

See also:

  • What are the differences between Rust's `String` and `str`?
like image 60
Shepmaster Avatar answered Nov 01 '22 23:11

Shepmaster