Using type alias inside struct

I have this simple example:

struct A
    const MyType = Int64
    x::MyType
end

a = A(1)

When I run it, I get a complaint about “unsupported const declaration on local variable”. Why doesn’t this work? If I lift the type alias outside the struct, it works. But doesn’t that mean I will export MyType to all files that include() this definition?

You can use a let block to make MyType only visible to the struct definition:

julia> let
         MyType = Int64
         
         struct A
           x::MyType
         end
       end

julia> a = A(1)
A(1)

julia> MyType
ERROR: UndefVarError: MyType not defined

I’m actually surprised that this works–I would have assumed that a struct definition inside a let block would not be allowed since it’s not at global scope, but it appears to work just fine.

1 Like

Maybe what you want is this?

struct A{ MyType <: Int64 }
   x :: MyType
end
1 Like

Usually you would put your functions inside a module, and you can choose what to export from that module.

4 Likes

And you’d still be able to access MyType explicitly with ModuleName.MyType if you need it later.

2 Likes