TransWikia.com

How can I get "Bar" from "Foo::Bar" in rust macro?

Stack Overflow Asked by Jason Sui on January 8, 2021

Original demand: I want to implement a macro that converts Foo::* to Bar::*.

Pseudo code will look like this:

macro_rules! convert_foo_to_bar {
    ($v: ty, $p: path) => (<$v>::$p.name)
}

// convert_foo_to_bar!(Bar, Foo::A) -> Bar::A

While $p.name refers to A.

One Answer

You can match the Foo::A using Foo::$variant:ident to get A as $variant like this:

macro_rules! convert_foo_to_bar {
    ($v: ty, Foo::$variant:ident) => (<$v>::$variant)
}

Playground

If you need to convert a variable, you will need to use a normal function such as this:

fn convert_foo_to_bar(foo: Foo) -> Bar {
  match foo {
    Foo::A => Bar::A,
    Foo::B => Bar::B,
    // .. for all of your variants
  }
}

Correct answer by Filipe Rodrigues on January 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP