I am trying to implement a flexible type system at runtime in Rust. This is what I have that works so far:
use std::borrow::Cow;
pub struct Float {
pub min: f64,
pub max: f64,
pub value: f64,
}
pub struct Text<'a> {
pub value: Cow<'a, str>
}
pub enum Value<'a> {
None,
Float(Float),
Text(Text<'a>),
}
This works as I want it to, and now I want a vector of itself (and a map would be the next step), so I added:
pub struct Vector<'a> {
pub value: Cow<'a, Vec<Value<'a>>>,
}
And extended the enum to:
pub enum Value<'a> {
None,
Float(Float),
Text(Text<'a>),
Vector(Vector<'a>),
}
Now I get an error message:
error[E0277]: the trait bound `Value<'a>: std::clone::Clone` is not satisfied
--> src/lib.rs:14:5
|
14 | pub value: Cow<'a, Vec<Value<'a>>>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::clone::Clone` is not implemented for `Value<'a>`
|
= note: required because of the requirements on the impl of `std::clone::Clone` for `std::vec::Vec<Value<'a>>`
= note: required because of the requirements on the impl of `std::borrow::ToOwned` for `std::vec::Vec<Value<'a>>`
= note: required by `std::borrow::Cow`
error[E0277]: the trait bound `Value<'a>: std::clone::Clone` is not satisfied
--> src/lib.rs:21:12
|
21 | Vector(Vector<'a>),
| ^^^^^^^^^^ the trait `std::clone::Clone` is not implemented for `Value<'a>`
|
= note: required because of the requirements on the impl of `std::clone::Clone` for `std::vec::Vec<Value<'a>>`
= note: required because of the requirements on the impl of `std::borrow::ToOwned` for `std::vec::Vec<Value<'a>>`
= note: required because it appears within the type `Vector<'a>`
= note: no field of an enum variant may have a dynamically sized type
I tried several ways to implement Clone
, but as a beginner I just ended up with countless other error messages. How do I get a vector of Value
into this system?
Why do I do this?
I have the following code to simplify the usage of Value
:
impl<'a> Value<'a> {
pub fn float_val(&self) -> f64 {
match self {
Value::None => 0.0,
Value::Float(f) => f.value,
Value::Text(t) => t.value.parse().unwrap_or(0.0),
}
}
pub fn str_val(&'a self) -> Cow<'a, str> {
match self {
Value::None => Cow::Owned("".to_string()),
Value::Float(f) => Cow::Owned(f.value.to_string()),
Value::Text(t) => Cow::Borrowed(&t.value),
}
}
}
This allows me to use it in functions like:
fn append_string(s1: &Value, s2: &Value) {
Value::Text(Text {
value: format!("{}{}", s1.str_val(), s2.str_val()),
})
}
I want the same for a vector, which I assume would be like:
pub fn vec(&'a self) -> Vec<Value> {
match self {
Value::Vector(v) => v.value,
_ => Cow::Owned(Vector { value: vec![] }),
}
}