This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/Lucretiel on 2023-09-14 04:14:09.


I’m pleased to announce my latest crate, typeof-literal. typeof-literal is a macro that can get the type of any literal (like "str" or 5) and any composite of literals (like (1, true, "hello"). It’s intended to support macro authors who generate trait implementations or function definitions in their macros, since it can be used to fill in return types or associated types if the expression in question is a literal.

use typeof_literal::typeof_literal;

/// This macro creates a `const fn` called `$name` that returns `$value`.
macro_rules! maker {
    ($name:ident => $value:expr) => {
        const fn $name() -> typeof_literal!{$value} {
            $value
        }
    }
}

maker! {ten => 10i16}
let value: i16 = ten();
assert_eq!(value, 10);

maker! {hello_world => "Hello, World"}
assert_eq!(hello_world(), "Hello, World");

// It works on composite types
maker! {tuple => (123, [0u8; 2], [1i64, 2, 3, 4], "Hello")};
assert_eq!(tuple(), (123i32, [0, 0], [1, 2, 3, 4], "Hello"));

// It also works on common macro literal-ish expressions
maker! {concatenated => concat!(1, 2, 3, "abc")}
assert_eq!(concatenated(), "123abc");

// We support blocks and other nested expressions, and can use `as` to support
// *any* arbitrary expression
maker! {computed => {
    let x = 1;
    let y = 2;
    (x + y) as i32
}}
assert_eq!(computed(), 3);