AnswerBun.com

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

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.

Stack Overflow Asked by Jason Sui on January 8, 2021

1 Answers

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!

Related Questions

Output is not shown in C

1  Asked on December 13, 2021 by cally

     

Have to print to screen for program to work

1  Asked on December 13, 2021

 

why ” is not pushed to stack to indicate the end of string?

0  Asked on December 13, 2021 by user11224591

   

Printing wrong text in list in Python

1  Asked on December 13, 2021 by n1ng4

         

Getting and saving application scope variable in Tomcat

3  Asked on December 13, 2021 by woodsman

   

Issue with Ansible Check and Diff Mode

1  Asked on December 13, 2021 by sunder

   

Java HashMap in Python Code throwing Error

1  Asked on December 13, 2021 by pritiraj

     

I am a little bit confused by the super().__init__()

4  Asked on December 13, 2021 by nick-yang

   

Formset not showing in Django 3

0  Asked on December 13, 2021 by ethan-roman

 

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved.