zig icon indicating copy to clipboard operation
zig copied to clipboard

Proposal: Add `with` block to temporarily rename arbitrary fields / variables

Open frmdstryr opened this issue 6 years ago • 3 comments

It'd be nice to have some sugar similar to the if (optional) |value| { syntax just for any arbitrary value.

with (mystruct.field) |*f| {
    // Now I don't have to repeat mystruct.field everywhere
    // and don't clutter the namespace
}
// f is undeclared here

The current method is to keep repeating mystruct.field everywhere or to copy the value or ptr to a variable in a block, eg

{
   var f = &mystruct.field;
   // do stuff here
}

but I'm not sure if the optimizer always knows to pull out the temporary variable in this case or not. I don't really want a pointer, I just want to not repeat myself.

That is all. May not be worth the effort but thought I'd ask.

frmdstryr avatar Mar 07 '20 22:03 frmdstryr

I personally don't like the fact that you need to add an indentation block just for one alias. It will get messy for multiple aliases.

with (mystruct.field1) |f1| {
	with (mystruct.field2) |f2| {
		with (mystruct.field3) |f3| {
		   ...
		}
	}
}

I would rather just have

{
	var f1 = &mystruct.field1;
	var f2 = &mystruct.field2;
	var f3 = &mystruct.field3;
}

Just my personal preference though.

tuket avatar Mar 11 '20 11:03 tuket

Agree. Without unpacking (https://github.com/ziglang/zig/issues/3897) this isn't all that useful for multiple fields.

frmdstryr avatar Mar 11 '20 12:03 frmdstryr

Just add using key word

hamad-almamari avatar Mar 11 '20 19:03 hamad-almamari