[−][src]Macro type_traits::size_of
Returns size of supplied expression at compile time.
Accepts both type and value.
Doesn't work with unsized values
Usage
use type_traits::size_of; let array = [0u8; 4]; assert_eq!(size_of!(array[0]), size_of!(u8)); assert_eq!(size_of!(array.len()), size_of!(usize));
This will fail to compile because Rust macro system is actually just syntax replacement It is not aware about actual properties of passed arguments
Anything that resembles type, will be tired as such As Rust lacks any utility to get type out of expression, you have to work it around by tricking macro into making something expression.
ⓘThis example deliberately fails to compile
use type_traits::size_of; let array = [0u8; 4]; assert_eq!(size_of!(array), size_of!(u32));
Instead you can append colon to tell macro to treat it as value
use type_traits::size_of; let array = [0u8; 4]; assert_eq!(size_of!(array,), size_of!(u32)); fn test<T>(val: &T) -> usize { size_of!(val,) } assert_eq!(test(&255u8), size_of!(usize)); // this will cause to return ptr size fn test2<T>(val: &T) -> usize { //We use special syntax * to tell macro to not create extra reference size_of!(*val) } assert_eq!(test2(&255u8), size_of!(u8));