Closed baoyachi closed 2 years ago
I want to do such a function to verify online whether json can serialize Rust structures normally.
The json string and the Rust struct are dynamically passed to rhai
at the front end. How doesrhai
convert this struct string
to the real struct of Rust
.
For a struct to be serializable, you need to put serde::Serialize
on it. Therefore, not just any struct, but serde::Serialize
marked structs.
You can probably impl a method on your struct type that takes the JSON string and attempts to deserialize it?
Then your Rhai script can simply call this method.
This structure is not predefined in rust code, but a dynamic rust struct generated by accepting input in rhai
This structure is not predefined in rust code, but a dynamic rust struct generated by accepting input in rhai
How would you "dynamically" generate a Rust struct? Rust programs are pre-compiled.
Do you plan to have Rhai generate Rust source code for subsequent compilation?
Do you plan to have Rhai generate Rust source code for subsequent compilation?
I think Rhai
can do more extensions after it has this function, but I'm not familiar with Rhai
now, but I'm interested in rhai
I think
Rhai
can do more extensions after it has this function, but I'm not familiar withRhai
now, but I'm interested inrhai
Rust is a compiled statically-typed language. There is no way to generate a dynamic data type at runtime.
You can, however, work directly with the standard rhai::Map
type which is an object map with dynamic properties. This may fit your purpose.
So, I need to convert my custom Rust dynamic structure to rhai::Map object by myself ?
Golang can do this, because of reflect:https://stackoverflow.com/questions/40559250/golang-dynamically-creating-member-of-struct. Rust how to do?
Golang can do this
That's called "reflection" (notice the calls to reflect
in that SO article). Rust doesn't have it, so it is impossible to do that in Rust.
ðŸ˜
So, I need to convert my custom Rust dynamic structure to rhai::Map object by myself ?
You can simply use rhai::Map
everywhere. It is a Rust type (an alias to BTreeMap
), it allows you to dynamically add/delete properties of any type, it does the same function as a struct (allowing you to look up property values), and it supports serialization to/from JSON.
Oh, this Rhai::Map can't be satisfied for the time being, because I need deterministic structures. Rhai::Map is dynamic and cannot be checked
In that case, there isn't a lot can be done...
Closing this for now. Putting wontfix
on it.
Not sure what you're asking for. Can you be more specific?
Typically a Rust struct is an object map in Rhai.