#Referencing an anonymous struct field

1 messages · Page 1 of 1 (latest)

median pecan
#

I am returning an anonyous struct from a function, something like: return .{ .a = 1, .b = 2 };

Question: is it possible to reference an already initialized field of the struct being created/returned, to initialize another one ?

I have tried: return .{ .a = 1, .b = .a + 1 };
But it doesn't work. I belive I need an outter reference, like a self. functionName.a doesn't work either.
I know a workaround is storing the values in consts before the return, but I just wanna know if it is possible to avoid that.

tired cipher
#

all fields are constructed together, you can't reference an earlier field's value

lament ingot
#

does iterating over the returned struct with std.meta.fields and using the field name work?

median pecan
#

Nope. Tried *std.meta.fields(MyType)[0].default_value.? but it complained it was unable to unwrap null (also tried without derref and other variations). And StructField does not have the actual value, just this default_value.

lament ingot
#

I'm sorry I misunderstood the original question I don't believe you can reference a struct prior to its creation

#
.{ .a = a, .b = a + 1 };

is probably what you're going to want to do or something like it

#

where a is previously defined ya