gtgt
#1
Is there anyway to destructure using variable names different from fields?

```
struct S
x::Int
y::Int
end
s = S(1, 2)
(; x, y) = s # ok
(; a, b) = s # error: Type S has no field a
```

In C++ I can do the following

```
struct S {
int x, y;
};
S s{1, 2};
auto [a, b] = s;
```

To do this you would have to do `a,b = s.a, s.b`

3 Likes

You can define iteration for your type (if that makes sense):

```
struct S
x::Int
y::Int
end
function Base.iterate(s::S, i = 1)
if i <= nfields(s)
return (getfield(s, i), i + 1)
else
return nothing
end
end
```

```
julia> for s in S(3,4)
@show s
end
s = 3
s = 4
julia> a, b = S(6, 1);
julia> a
6
julia> b
1
```

4 Likes

If you use your structure as a simple â€śdata containerâ€ť (not using it in dispatching etc.), then maybe a named tuple would fit you?

```
julia> s = (x=1, y=2)
(x = 1, y = 2)
julia> s[:x]
1
julia> s.x
1
julia> a, b = s
(x = 1, y = 2)
```

or just a tuple

```
julia> s = (1, 2)
(1, 2)
julia> s[1]
1
julia> a, b = s
(1, 2)
```

1 Like

Edit: Ignore my answer, because I missed the point of the question â€¦

```
using UnPack
@unpack a, b = s
```

1 Like