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.
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.
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With