macro_rules! expr_as_phantom {
    ($e:expr) => { ... };
}
Available on crate feature phantom only.
Expand description

Gets the type of an expression as a PhantomData, without evaluating the expression.

Example

use core_extensions::expr_as_phantom;

use std::marker::PhantomData;

fn type_name<T>(_: PhantomData<T>) -> &'static str {
    std::any::type_name::<T>()
}

let mut list = vec![0, 1];

// This block passed to the `expr_as_phantom` macro doesn't run.
let name = type_name(expr_as_phantom!({
    list.extend(2..1_000u16);
    list
}));
 
assert!(name.contains("Vec"));
 
assert_eq!(list, [0, 1])

Const callable

This macro works in const contexts, since Rust 1.46.0.

use core_extensions::{as_phantom, expr_as_phantom};

use std::marker::PhantomData;

const fn size_of_phantom<T>(_: PhantomData<T>) -> usize {
   std::mem::size_of::<T>()
}

const fn size() -> usize {
   let tup = (0u8, 116, [3u64, 4]);

   size_of_phantom(expr_as_phantom!( tup.2[0] ))
}

assert_eq!(size(), 8);