Crate name macro

Is there an equivalent of module_path in std - Rust that returns only the first part, the crate name ?

You can split the return value of module_path:

fn crate_name() -> &'static str {
    let path = module_path!();
    path.split_once("::").map_or(path, |(first, _)| first)
}

I was expecting a compile-time solution, if possible. Otherwise I'll mark your response as solution.

How much compile-time? I believe it's possible to implement this as a const fn by manually and recursively searching for the first :, but I don't think such splitting can be performed at the macro level. If a macro expansion time solution is desired, you can always read CARGO_PKG_NAME from the environment from within a procedural macro.

I found the const_str - Rust crate that can split in const context.

const MODULE_PATH: &'static str = module_path!();
const LIB_NAME: &'static str = const_str::split!(MODULE_PATH, "::")[0];
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.