Is it possible to implement something like Haskell's Dynamic value holder
in Rust? (This would be similar to supporting C++'s dynamic_cast).
Basically, something like this:

pub struct Dynamic { ... }
impl Dynamic {
    pub fn put(value: ~T) { ... }
    pub fn get() -> Option<T> { ... }
}

I guess this would require unsafe code... even so, it seems to me that Rust
pointers don't carry sufficient meta-data for the above to work. A possible
workaround would be something like:

pub struct Dynamic { type_name: ~str, ... }
impl Dynamic {
    pub fn put(type_name: &str, value: ~T) { Dynamic { type_name:
type_name, ... } }
    pub fn get(&'a self, type_name: &str) -> Option<&'a T> {
assert_eq!(type_name, self.type_name); ... } }
}

And placing the burden on the caller to always use the type name "int" when
putting or getting `int` values, etc. This would still require some sort of
unsafe code to cast the `~T` pointer into something and back, while
ensuring that the storage for the `T` (whatever its size is) is not
released until the `Dynamic` itself is.

(Why do I need such a monstrosity? Well, I need it to define a
`Configuration` container, which holds key/value pairs where whoever sets a
value knows its type, whoever gets the value should ask for the same type,
and the configuration can hold values of "any" type - not from a predefined
list of types).

Is such a thing possible, and if so, how?

Thanks,

Oren Ben-Kiki
_______________________________________________
Rust-dev mailing list
Rust-dev@mozilla.org
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to