Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Giving different variable names when destructuring structs #52191

Open
theogf opened this issue Nov 16, 2023 · 4 comments
Open

Giving different variable names when destructuring structs #52191

theogf opened this issue Nov 16, 2023 · 4 comments

Comments

@theogf
Copy link

theogf commented Nov 16, 2023

Right now it's possible (and great) to do

struct Foo
 a
 b
end
(; a, b) = Foo(2, 3)

However, in some cases (we want to destructure multiple Foo in the same scope) it would be great to be able to directly use different variable names and do something like

(; a1 = a, b1 = b) = Foo(2, 3)
(; a2 = a, b2 = b) = Foo(1, 2)

There is a similar pattern in Rust described here

@StefanKarpinski
Copy link
Member

It's not at all obvious to me whether the name of the field should go on the left or right side of the = in this construct, which makes me kind of skeptical of adding this. Pretty sure I would always forget. You were constructing a named tuple, you would write (; a = a1, b = b1) rather than (; a1 = a, b1 = b)... which made me curious if Rust really did it this way... and indeed, they do not. But that only reinforces my point about how unobvious the ordering is considering that you got it wrong in the motivating example.

@theogf
Copy link
Author

theogf commented Nov 17, 2023

That's a really good point. I was thiking as we assign a1 and b1 rather than the opposite, having them on the LHS would make more sense, one could see the RHS as the "scope" of the struct.

But the fact that there is this ambiguity definitely would make it complicated.

how unobvious the ordering is considering that you got it wrong in the motivating example.

I was not trying to reproduce the exact Rust syntax, just wanted to show that they were doing something similar.

@Pangoraw
Copy link
Contributor

Pangoraw commented Nov 17, 2023

This is also discussed in #51940.

As another example, JavaScript has syntax for both setting a default value and assigning the name (field names are on the left, variables on the right):

const { a: a1 = aDefault, b = bDefault } = obj;

@stevengj
Copy link
Member

stevengj commented Nov 27, 2023

Yes, as I commented in the other issue mentioned by @Pangoraw, I would prefer to use = for default values, much like keyword arguments.

Analogous to JavaScript, if we want to have renaming we could use Julia's own using syntax of as, i.e.

(; a as a1 = aDefault, b = bDefault, c as c1) = obj

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants