Karl Roldan
Karl Roldan

Reputation: 387

What's the Julia way of creating an empty object with a parameterized type?

Suppose, we have the following data structure

struct MyStruct{T}
    t :: Union{Nothing, T}
end

and we want to allow the user to initialize the struct without adding any data such as MyStruct{T}().

So far, I've tried

MyStruct() where {T} = MyStruct{T}(nothing)

which I try to instantiate with

x = MyStruct{Int}()

which tells me

ERROR: MethodError: no method matching MyStruct{Int64}()
Closest candidates are:
  MyStruct{T}(::Any) where T at REPL[1]:2
Stacktrace:
 [1] top-level scope
   @ REPL[4]:1

What's the idiomatic way to do this?

Upvotes: 3

Views: 862

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69869

Is this what you want?

julia> MyStruct{T}() where T = MyStruct{T}(nothing)

julia> MyStruct{Int}()
MyStruct{Int64}(nothing)

Upvotes: 2

Related Questions