# Advice for structure

**URL:** <https://discourse.julialang.org/t/advice-for-structure/11260>\
**Category:** Performance\
**Created:** [May 30, 2018, 1:39pm UTC](https://discourse.julialang.org/t/advice-for-structure/11260 "2018-05-30T13:39:37Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![rveltz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rveltz/32/2707_2.png) [@rveltz](https://discourse.julialang.org/u/rveltz)\
**Post date:** [May 30, 2018, 1:39pm UTC](https://discourse.julialang.org/t/advice-for-structure/11260/1 "2018-05-30T13:39:37Z")

</div>

Hi,

I am working with couples of vectors x,p where the size of x (resp. p) is fixed.  
I thought about using

```julia
mutable struct Cp{T}
  x::Vector{T}
  p::Vector{T}
end

```

However, I would like to overload the operators so that if `u = Cp(rand(3),rand(4))`, I could do `3*u`, `v = copy(u)` or compute `u-2v` for example.

Is there a good way for doing this?

Thank you for your help,

Best regards

---

<div class="post-metadata">

**Author:** ![JeffreySarnoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreysarnoff/32/1980_2.png) [@JeffreySarnoff](https://discourse.julialang.org/u/JeffreySarnoff)\
**Post date:** [May 30, 2018, 2:09pm UTC](https://discourse.julialang.org/t/advice-for-structure/11260/2 "2018-05-30T14:09:35Z")

</div>

Yes (the short answer). In general, this is accomplished using type-directed dispatch with function signatures that use your type `Cp{T}`.

```julia
import Base: +, -, *

mutable struct Cp{T}
    x::Vector{T}
    y::Vector{T}
end

function (*)(a::Real, cp::Cp{T}) where {T}
     newx = a .* (cp.x)
     newy = a .* (cp.y)
     result = Cp{T}(newx, newy)
     return result
end

function (-)(a::M, b::M) where {T, M<:Cp{T}}
    @assert length(a.x) == length(b.x) == length(a.y) == length(b.y)
    newx = a.x .- b.x
    newy = a.y .- b.y
    result = Cp{T}(newx, newy)
    return result
end

julia> a = Cp([1,2,3],[4,5,6])
Cp{Int64}([1, 2, 3], [4, 5, 6])

julia> b = 3a
Cp{Int64}([3, 6, 9], [12, 15, 18])

julia> 8a - 2b
Cp{Int64}([2, 4, 6], [8, 10, 12])

```

```julia

```

---

<div class="post-metadata">

**Author:** ![rveltz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rveltz/32/2707_2.png) [@rveltz](https://discourse.julialang.org/u/rveltz)\
**Post date:** [May 30, 2018, 2:58pm UTC](https://discourse.julialang.org/t/advice-for-structure/11260/3 "2018-05-30T14:58:27Z")

</div>

Wow, you are fast.

Thank you for your help.
