how to return a new instance in julia

Viewed 96

how can I return a new instance from a struct within a function in Julia?

function generateField(type, default, description, max, min)
 return Field{type}(default,description,min,max)
end

I have a struct called Field. I just used Java logic hier and it did not work for sure :)

    struct Field{T}
   type::T
   default::T
   description::String
   min::T
   max::T
  function Field{T}(description,min,max) where {T}
       new{T}(description, min, max)
  end 
end
1 Answers

Just use deepcopy(obj) - it will make a copy of your struct object (assuming this is what you need):

julia> mutable struct Field2{T<:Real}
       a::T
       b::Vector{Float64}
       end

julia> x = Field2{Int}(5,[4.5])
Field2{Int64}(5, [4.5])

julia> y = deepcopy(x)
Field2{Int64}(5, [4.5])

julia> y == x
false

Note that x and y point to different variables and hence x == y yields false. To compare by value one would need to iterate over all struct fields.

For this struct a function generating it could be defined as :

function f(a::T, b::Vector{Float64}) where T <: Real
   return Field2{T}(a,b)
end

And used as:

julia> f(1//2, [3.5])
Field2{Rational{Int64}}(1//2, [3.5])

Finally, note that the function generating an object can have the same name as its type - in that case you are generating new constructor:

julia> Field2(a::T) where T<:Real = Field2{T}(a,Int[]);

julia> Field2(2)
Field2{Int64}(2, Float64[])
Related