What types are allowed inside struct?

Hi, I am a little confused about what types are allowed to be declared for fields inside a struct. For example,

struct Foo
       list:: Tuple{Int64}
end

gives me an error that says " cannot covert object of type Tuple{Int64} to Tupule{}" when I try to instantiate the object, says foo((1,2)). However, I instead do

struct Foo
       list:: Tuple
end

It is fine. This is the same if I try to declare the type of the fieldnames to be a particular kind of dictionary. I think I am misunderstanding something very fundamental here. Any clarification or pointing to where to read in the document would be gladly appreciated.

All types are allowed to be fields of a struct. The issue in your case is that the type Tuple{Int64} means a tuple with exactly one Int64. The type of (1, 2) is Tuple{Int64, Int64} so you can’t assign that to a field of type Tuple{Int64}.

3 Likes

Oh, thanks you. My bad in my mind I thought Tuple{Int64} implicitly impiles (int64, int64).

Yeah, I think people often think specifically of 2-tuples when they say “tuple”, but there’s nothing special about a 2-element tuple in Julia. You can have a tuple with any number of arguments, and the type signature just shows every element: Tuple{Int}, Tuple{Int, Int}, Tuple{Int, Int, Int}, etc.

But if you want a more convenient shorthand, you can also use NTuple{N, Int} to express a tuple of N Ints:

julia> Tuple{Int} === NTuple{1, Int}
true

julia> Tuple{Int, Int} === NTuple{2, Int}
true

julia> Tuple{Int, Int, Int} === NTuple{3, Int}
true
6 Likes