Serialize to Rust?

I want initialise struct in const context without usage of lazy_static and similar stuff.
Just plain constant.
But current stable rustc can no evaluate code that I need in const context (the main problem are math functions, like sin, sqrt and so on).

So the part of calculation is simple, I use build script and calculate what I need.
But how I save result back to Rust?

Is any serde like crates, where I can do something like this:

struct Foo {
  a: f64,
  b: f64,

serde_rust::to_code(&Foo { .. })

where serde_rust::to_code generates Rust code as string?

Heya, you could:

  1. Generate code in like you mention, and
  2. Use the include! macro to include the generated code as part of the source code.

I've done something like that in this which writes to "${OUT_DIR}/", and included it in

peace :v:

I can calculate the resulting value of Foo.
The problem exactly in code generation.
I use Foo in as type. In other words,
I use module where Foo defined from my

You could do something as simple as this.

#[derive(Default, Debug)]
struct Foo {
  a: f64,
  b: f64,

fn static_foo(name: &str, foo: &Foo) -> String {
    format!("static {name}: Foo = {foo:?};")

fn main() {
    // `Debug` format is not guaranteed
    // (Roll your own `Display` if preferred)
        "static FOO: Foo = Foo { a: 0.0, b: 0.0 };",
        static_foo("FOO", &Foo::default())
    // ... stuff ...
1 Like

Yeah, this is almost what I want. The problem is that default Debug implementation uses unknown precision of float points. But I suppose I can implement my own Debug implementation of Foo, that replace print of all float values with hex float.

I can't find a reference document to cite (best I could quickly find is things like this PR where it was done), but Rust's floating-point printing will not lose precision — it will print enough digits to reproduce the number, unless you ask for a specific number of digits.


There is databake - Rust. Check out also Rust Zürisee, Dec 2022: Supercharging Zero-Copy Deserialization - YouTube


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.