1

To wit:

use std::fmt;

// Element types
const INTEGER: &'static str = "INTEGER";
const FLOAT: &'static str = "FLOAT";
const STRING: &'static str = "STRING";

#[derive(Debug)]
struct Element<T> {
    mt_type: &'static str,
    mt_value: T,
}
impl<T: fmt::Display> fmt::Display for Element<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Element({}, {})", self.mt_type, self.mt_value)
    }
}

struct Parser {
    text: String,
    pos: usize,
    current_element: Element, // Here there should be something to hold different Elements at different times...
}

I would need current_element to hold a Element<i64>, a Element<f64>, and a Element<String> in the same struct at different times; I was reading the Rust guide and it seems that all solutions point towards making the struct Parser generic, yet if I do that then at run-time I am committed to use a different Parser for a different Element type.

An ugly way to solve this is to get all values inside Element as strings and then convert them to the proper type when needed, but then the overhead would be big...

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Davide Del Papa
  • 378
  • 2
  • 9
  • You cannot — Rust sizes structs based on their members, so an `Element` has a different size from `Element`. When you put an `Element` into your `Parser`, then the size of the `Parser` depends on the generic type. The alternative is to have a single type that represents all possibilities. A *trait object* or an enum would be the go-to choices. – Shepmaster Oct 20 '17 at 18:09
  • Understood. Thank you for pointing me to the right answer. – Davide Del Papa Oct 20 '17 at 21:26

0 Answers0