#Inlining expression

1 messages · Page 1 of 1 (latest)

bright brook
#

I have code like this:

var random: std.rand.Random = undefined;

pub fn main() !void {
  var tt = std.rand.DefaultPrng.init(@intCast(std.time.milliTimestamp()));
  random = std.rand.DefaultPrng.init(@intCast(std.time.milliTimestamp())).random();
}

I'd like to inline the creation of tt, but I cannot replace random = tt.random() with random = std.rand.DefaultPrng.init(@intCast(std.time.milliTimestamp())).random(); as this gives me the error "error: expected type '*rand.Xoshiro256', found '*const rand.Xoshiro256'"

Can I somehow avoid it by casting?

livid flax
#

No, you need to have a local variable here. When you use .random(), the object you get is a wrapper which is essentially a pointer to tt; the state of the PRNG is still encapsulated in tt itself, meaning that object must survive. Using a temporary here - i.e. doing DefaultPrng.init(...).random() - does not make the lifetime of the temporary clear, and by the language spec, the temporary might be clobbered in future statements within the function. As such, Zig makes the pointer to the temporary const to discourage this kind of bug.