Manish Gupta
Manish Gupta

Reputation: 4656

How to map a string to a struct?

I have some structs like:

pub struct A {}

pub struct B {}

I want to map these structs to a string mapping:

let s = match x {
    "a" => A {},
    "b" => B {},
    _ => panic!()
} 

like a Python dict. How can I do this in Rust?

Upvotes: 1

Views: 1506

Answers (1)

The Quantum Physicist
The Quantum Physicist

Reputation: 26256

Rust is not like Python. In Rust, you have to know the size of all your objects on the stack at compile time. If not, then you have to use dynamic objects that are allocated on the heap.

In C++ or similar languages, you'd create a base class where both your classes inherit from it. This way, you can dynamically create an object at run-time, with a type that you choose based on a run-time condition. This is the classical way of doing things.

In Rust, the alternative is called "trait objects", where both your classes implement the same trait (so that trait plays the role of a base class). Here's how you do it:

trait C {}

impl C for A {}

impl C for B {}

pub struct A {}

pub struct B {}

fn main() {
    println!("Hello, world!");
    let x = "a";
    let s: Box<dyn C> = match x {
        "a" => Box::new(A {}),
        "b" => Box::new(B {}),
        _ => panic!()
    };
}

Box is a safe container for a pointer, which will be deallocated when you exit this scope (unless you choose to pass it somewhere else).

Play with this code on playground

Upvotes: 5

Related Questions