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"));
unknown
}};
}
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: Rust Playground