I'm trying to implement different data types. I thought I'm very smart with using a struct which contains information about the data type and the content. I hope that the option type doesn't interfere with my size, as this would render the use of a union useless. Anyway I'm having problems retrieving the data.
pub struct Value {
data_type: DataType,
data: Option<Data>,
}
pub enum DataType {
Bool,
Number,
Nil,
}
#[repr(C)]
pub union Data {
boolean: bool,
number: f64,
}
pub trait IsData{}
impl IsData for bool{}
impl IsData for f64{}
pub trait InputConverter<T> {
fn convert_input(data: T) -> Data;
}
impl InputConverter<bool> for bool {
fn convert_input(data: bool) -> Data {
Data { boolean: data }
}
}
impl InputConverter<f64> for f64 {
fn convert_input(data: f64) -> Data {
Data { number: data }
}
}
impl Value {
pub fn new<T>(data_type: DataType, data: T) -> Self
where
T: InputConverter<T>,
T: IsData
{
let data: Option<Data> = match data_type {
DataType::Bool => Some(T::convert_input(data)),
DataType::Number => Some(T::convert_input(data)),
DataType::Nil => None,
};
Self {data_type, data}
}
pub fn get_data<T: IsData>(value: &Value) -> Option<&T>{
match value.data_type{
DataType::Bool => unsafe{Some(&value.data.unwrap().boolean)},
DataType::Number => unsafe{Some(&value.data.unwrap().boolean)},
DataType::Nil => None
}
}
}