slint icon indicating copy to clipboard operation
slint copied to clipboard

Default values for struct fields

Open ogoffart opened this issue 2 years ago • 3 comments

It is often requested to have default values for struct fields

It could look like this:

struct Player {
     score: int = -1,
     name: string = "John Smith",
}

Then, when initialized, or converted from a struct with less fields, the other fields are initialized with thei default value:

component X {
   // initialized to default values
   property <Player> player1;
   // score will be -1
   property <Player> player2: { name: "Alex" };
}

The Default implementation of the rust structure or C++ default constructor must initialize the fields accordingly.

ogoffart avatar Jun 20 '23 05:06 ogoffart

Straightforward syntax, and very sensible. I'm much in favor.

tronical avatar Jun 20 '23 06:06 tronical

I see myself mixing up : and = as we use : for assignments pretty much everywhere else.

Could we maybe do something like

struct Player {
     <int> score: -1,
     <string> name: "John Smith",
}

That is of course breaking the existing struct definition syntax... which I can remember well as "assigning a type to the field name":-)

hunger avatar Jun 21 '23 09:06 hunger

Yeah, there's a bit of a syntax conflict here. Using = in this case seems a bit out of place, but : clashes with the type specifier.
I wouldn't be against changing the struct field declaration to be more akin to property declaration, like @hunger suggested. It would make Slint's syntax more consistent overall, lowering the learning curve a bit.

Tmpod avatar Apr 08 '24 16:04 Tmpod