# How does copying slices work?

``````julia> data=[1,2,3,4,5,6,0,0,0]
9-element Vector{Int64}:

julia> data[6:9].=data[3:6]

julia> data
9-element Vector{Int64}:
1
2
3
4
5
3
4
5
6
``````

why in this example data =6 and not =data?
I’m fine with it working like this, of course, I just want to understand how this result is achieved.

same question for

``````copyto!(data,6,data,3,4)
``````
1 Like

Specifically there `data[3:6]` is materialized into a new array first, and then the elements are copied (views in Julia copy). That is identical to:

``````julia> data2 = data[3:6]
4-element Vector{Int64}:
3
4
5
6

julia> data[6:9] .= data2
4-element view(::Vector{Int64}, 6:9) with eltype Int64:
3
4
5
6

julia> data
9-element Vector{Int64}:
1
2
3
4
5
3
4
5
6
``````

Another question is how this is achieved:

``````julia> data=[1,2,3,4,5,6,0,0,0];

julia> data[1:9] .= @view(data[9:-1:1])
9-element view(::Vector{Int64}, 1:9) with eltype Int64:
0
0
0
6
5
4
3
2
1
``````

At some point that ought to need some intermediate.

1 Like

because

``````julia> data[6:9]
4-element Vector{Int64}:
6
0
0
0
``````

and

``````
julia> data[3:6]
4-element Vector{Int64}:
3
4
5
6
``````

so the `.=` will assign those values elementwise. See the docs on Vectorized “dot” operators

`data[6:9].=data[3:6]`

is equivalent to:

``````data = data
data = data
data = data
data = data
``````

As `data` is `9`, the new 9th position of data is 6.

EDIT: you are right, I didn’t look at the problem properly…

I don’t think your argument is correct, or I misunderstood it (following it we’d have `data <- data <- data` which is not the case and that’s what OP was asking.

@lmiq is right that `data[3:6]` is materialised first and then the assignment is done for the 3 entries.

Note that this is not the case:

``````julia> data = [1,2,3];

julia> data = @view(data[3:-1:1])
3-element view(::Vector{Int64}, 3:-1:1) with eltype Int64:
3
2
1

julia> data = [1,2,3];

julia> data = data
data = data
data = data
data
3-element Vector{Int64}:
3
2
3
``````

Semantically, the broadcast will work as if the array on the right is first copied into a new array (I’m not sure if non-copying is guaranteed always, I guess not, sometimes an intermediate is needed).

1 Like

the result could be obtained with an “algorithm” equivalent to this

``````data = data
data = data
data = data
data = data
``````