# Error when assigning a struct, via broadcast, to an array of structs

**URL:** <https://discourse.julialang.org/t/error-when-assigning-a-struct-via-broadcast-to-an-array-of-structs/46165>\
**Category:** General Usage\
**Created:** [September 6, 2020, 11:37pm UTC](https://discourse.julialang.org/t/error-when-assigning-a-struct-via-broadcast-to-an-array-of-structs/46165 "2020-09-06T23:37:10Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![purplishrock](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/purplishrock/32/13451_2.png) [@purplishrock](https://discourse.julialang.org/u/purplishrock)\
**Post date:** [September 6, 2020, 11:37pm UTC](https://discourse.julialang.org/t/error-when-assigning-a-struct-via-broadcast-to-an-array-of-structs/46165/1 "2020-09-06T23:37:10Z")

</div>

I’m assigning a value, a single value, to an array of structs using an array to do the indexing. Let me jump straight to my MWE and the punch line

```julia
[1] x[ii] .= a

```

gives an error message, but

```julia
[2] x[ii] .= [a]

```

does not. And it makes sense that it works when you look at the error message, as ‘[a]’ has a length and ‘a’ does not. What I can’t figure out, of course, is why the error message shows up in the first place. The same example that uses an array of Int, Float64, etc… instead of a struct doesn’t show the same behavior, i.e. I can use form [1] and not get an error.

```julia
struct Foo
    a
end

x = Array{Foo,3}(undef,5,4,3)
y = randn(5,4,3)

for i=1:size(x,1)
    for j=1:size(x,2)
        for k=1:size(x,3)
            x[i,j,k] = Foo(y[i,j,k])
        end
    end
end

ii = y .< 0.0

a = Foo(0.0)

x[ii] .= a

ERROR: LoadError: MethodError: no method matching length(::Foo)
Closest candidates are:

```

---

<div class="post-metadata">

**Author:** ![hendri54](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/hendri54/32/9621_2.png) [@hendri54](https://discourse.julialang.org/u/hendri54)\
**Post date:** [September 7, 2020, 12:00am UTC](https://discourse.julialang.org/t/error-when-assigning-a-struct-via-broadcast-to-an-array-of-structs/46165/2 "2020-09-07T00:00:23Z")

</div>

You need

`Base.Broadcast.broadcastable(q::Foo) = Ref(q)`

Cf [Broadcasting structs as scalars - #6 by cossio](https://discourse.julialang.org/t/broadcasting-structs-as-scalars/14310/6)

---

<div class="post-metadata">

**Author:** ![purplishrock](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/purplishrock/32/13451_2.png) [@purplishrock](https://discourse.julialang.org/u/purplishrock)\
**Post date:** [September 7, 2020, 12:54am UTC](https://discourse.julialang.org/t/error-when-assigning-a-struct-via-broadcast-to-an-array-of-structs/46165/3 "2020-09-07T00:54:09Z")

</div>

ty!

that’s an interesting thread too.
