How do I attach size to a type?

I want to make a statically sized bit array, something like

Bits{5} = [0,0,0,0,0]
Bits{N} = [0,...] with length of N

I want to restrict N to an integer. What do I put in the struct type declaration?

struct Bits{???}
    storage
end

I’ve tried:

  1. Bits{N<:Integer}
  2. Bits{N<:Tuple}
  3. Bits{N<:Tuple{<:Integer}}
  4. abstract type Bits{N} end
  5. abstract type Bits5{N<:Integer} end
  6. Bits{N<:BaseType}

1 can be declared, but when I try to use the struct it errors:

julia> Bits{4}
ERROR: TypeError: in Bits, in N, expected N<:Integer, got Int64

2 kind of works, but then Tuple type can accept everything

julia> Bits2{Tuple{2,pi}}
Bits2{Tuple{2,π}}

3 fails like 1

julia> Bits3{Tuple{4}}
ERROR: TypeError: in Bits3, in N, expected N<:(Tuple{#s1} where #s1<:Integer), got Type{Tuple{4}}

4 kinda works but it can accept everything

julia> Bits4{pi}
Bits4{π}

5 fails

julia> Bits5{10}
ERROR: TypeError: in Bits5, in N, expected N<:Integer, got Int64

6 can’t be declared

julia> struct  Bits6{N<:BaseType}
           asdf
       end
ERROR: UndefVarError: BaseType not defined

This is saying that N is a type that is a subtype of Integer. You want N::Integer (N is an instance of Integer), but AFAIK there is no way to declare this for type parameters.

Just declare Bits{N} and then enforce N being an integer in the constructor. See also how StaticArrays.jl does it.

1 Like