0
struct Foo {
    bar: i32,
}

let foo_var = Foo { bar: 16 };

// I want to do something like this
foo_var.new_field: u8 = "new field".to_string();

// which lets me then call
println!("{}", foo_var.new_field);
// which would print "new field"

I know I could:

  1. implement it as a function, but I want to have a consistent "style", so I want to avoid parenthesis for foo_var.new_field().

  2. implement it as a default, but it would be cool if I could implement this in another script (like you can do with impl for functions) without always adding a field to the struct and the default.

Shepmaster
  • 274,917
  • 47
  • 731
  • 969
  • 4
    No, it is not possible, because Rust statically resolves struct fields at compile time. For that to work, you would need to write that logic in code, such as encoding the fields as the keys of a `HashMap`. – SE_net4 the downvoter Nov 04 '20 at 14:09
  • @E_net4iscleaningup TBF that it's statically typed doesn't make it impossible, you could have something like this in a language with a structural type system (though I don't think it would be possible to add the field in-place, you'd create a new record with a different type and an additional field). – Masklinn Nov 05 '20 at 09:11

0 Answers0