#Is it possible to get a pointer to an optional payload?

1 messages · Page 1 of 1 (latest)

thick flint
#

I have a function that does:

fn set(i: *u64) void {
   i.* = 2
}

I have an optional:

var result: ?u64 = null;

And I want to do this without the tmp var:


fn doit(result: *?u64) void {
  var tmp: u64 = undefined;

  set(&tmp);

  result.* = tmp;
}

const S = struct {
  result_here: ?u64,
};

const result_struct = S{.result_here = null};
doit(&result_struct.result_here);
loud dome
#

Just do result = @as(u64, undefined); and then do set(&result.?);

thick flint
#

Ah I simplified my example too much, let me edit it

weak oxide
#

I assume you can't make the function return u64?

thick flint
#

that is closer to reality

#

The pointer is important, I should not have removed it

weak oxide
#
const result_struct = S{.result_here = @as(u64, undefined)};
set(&result_struct.result_here.?);
#

same thing as IK did earlier

#

@thick flint

loud dome
#

Ye. The main thing here is that, while the optional is null, the place where the value would otherwise be placed is considered "inaccessible", or just invalid. So the way to make it accessible is to flip the flag that says "it's null", and the way to do that is the assign a value. Of course, that could be a wasteful copy, but luckily, assigning undefined is a noop in optimized builds, so here it's tantamount to just flipping the "null bit"

thick flint
#

ok I get it

#

thanks

#

yeah it works, actual code:

            dest.* = @as(O.child, undefined);
            try get(allocator, &dest.*.?, env, term);

That get function converts erlang value to zig and is recursive.

loud dome
#

Fancy