Using unknown type methods in macro

I'm playing with macros and I found myself in a situation where I don't know how to make it compile. I want to call method on unknown type which I know should exist. Compiler should decide the type from the lvalue but for reason he doesn't do that.

Here is a mre

#[derive(Debug, Default)]
struct Inner {
    value: String,

#[derive(Debug, Default)]
struct Unknown {
    field: Option<Inner>,

impl Inner {
    fn create_from_str(value: &str) -> Self {
        Inner {
            value: value.to_owned(),

macro_rules! create_default {
    ($t:ty) => {{
        let mut unknown = <$t>::default();
        unknown.field = Some(<_>::create_from_str("hello"));

fn main() {
    let unknown = create_default!(Unknown);
    eprintln!("{:?}", unknown);

The question here is if I can make it work with only changin body of macro. The only two possibilities I see are adding another macro parameter to call method directly or add some trait like CreateFromStr and call it like CreateFromStr::create_from_str. But they both have theirs drawbacks.

Playground link:

You cannot do this because Rust compiler doesn't exclude the possibility of some other types implement the same method:

struct Other;
impl Other {
    fn create_from_str(value: &str) -> Inner { unimplemented!() }

Traits must be used for the type inference.

The remaining possibility is somehow extracting the type Inner from unknown.field value. However, Rust doesn't have C++'s decltype equivalent and I don't think it is possible to do this currently. It seems like typeof is a reserved keyword and there is an RFC but is not accepted well and I don't think it will be implemented anytime soon.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.