1

Example struct that will be created and serialized often:

pub struct PriceMessage
{
    pub message_type: String,  // this will always be "price"
}


I want "message_type" to always equal e.g. "price" in order to save allocating a new string every time I create and serialize this struct using serde_json crate.

SpaceMonkey
  • 4,143
  • 5
  • 38
  • 60
  • 2
    Does this answer your question? [How do I declare a "static" field in a struct in Rust?](https://stackoverflow.com/questions/26549480/how-do-i-declare-a-static-field-in-a-struct-in-rust) – Nathaniel Ford Jun 24 '22 at 22:16
  • 1
    Also you can only use `&str` as the type of const variables, not `String` for now. – Sprite Jun 24 '22 at 22:42
  • @NathanielFord nope – SpaceMonkey Jun 25 '22 at 12:57
  • @Sprite and how do I thenset it to a constant string? – SpaceMonkey Jun 25 '22 at 12:57
  • Your intention doesn't make much sense. A struct will allocate some amount of space in memory, equal to the size needed. Assuming you get what you want, that memory will *always* be allocated with the static string you select. So, regardless of how you set this up (and I think the linked duplicate question is as close as you can get), you will be allocating a new string every time. The alternative is to have a function that returns a constant as part of the struct impl. Beyond that, it's unclear why the offered solutions don't meet your requirement. – Nathaniel Ford Jun 26 '22 at 18:01
  • @NathanielFord sorry if I'm misunderstanding. I thought that when I call String::new("something") it is extra memory that I can avoid doing. I imagined I could have a constant string (fixed in the binary) and have the struct point to that string instead of creating a copy of that string every time I create the struct. – SpaceMonkey Jul 03 '22 at 10:08

1 Answers1

0

If you wanted to have a compile constant default string value for a field, that could at run time later be replaced by a heap allocated string, you could do something like this:

pub struct SomeStruct {
    pub some_field: Cow<'static, str>,
}

impl SomeStruct {
    const SOME_FIELD_DEFAULT: Cow<'static, str> = Cow::Borrowed("Foobar!");

    pub fn new() -> Self {
        Self {
            some_field: Self::SOME_FIELD_DEFAULT,
        }
    }
}

However if you want to have an actually constant field, this doesn't really make much sense in rust, and you should consider just using an associated constant.

Ivan C
  • 1,772
  • 1
  • 8
  • 13