Hey all, I'm just starting out with Rust, and I'm strugling a bit with what the best way to define a set of types that can be used to create more complex ones.
Think of JSON, where you have your scalar types (strings, numbers, bools) which can then be used to create composite types (objects, arrays). In order for the composite types to be created, it would be useful to "group" the types in a generic type, but it would be also really useful if we could reference the individual types as well on their own.
Initially enums seemed like the way to go.
pub enum Value {
String(String),
Int64(i64),
Bool(bool),
Map(HashMap<String, Value>),
Array(Vec<Value>),
// ...
}
This works pretty well for the most part, but the downside is that I can't use the underlying enum types directly.
pub struct Test {
pub v: Value,
pub i: Value::Int64, // INVALID
^^^^^^^^^^^^
|
not a type
help: try using the variant's enum: `crate::Value`
}
The other options I could think/find are to define either a struct or a tuple for each type.
pub struct String {
pub value: String,
}
pub struct Int64 {
pub value: i64,
}
pub struct Bool {
pub value: bool,
}
// ...
pub enum Value {
String(String),
Int64(i64),
Bool(bool),
// ...
}
pub struct Test {
pub v: Value,
pub i: Int64, // Valid, but horrible to work with
}
// ...
let test = Test {
v: Value::Int64(Int64 { value: 42 }), // Horrible
i: Int64 { value: 42 }, // A bit annoying
};
// ...
let i = test.i.value; // Very annoying
This is not really fun to work with, and I'm not sure if it's even the best way to go about it.
Are there any other/better ways to go about this?
Thank you very much in advance.
Regards, geoah