Global const in struct

In #32407 I saw

struct _GLOBAL_RNG <: AbstractRNG
    global const GLOBAL_RNG = _GLOBAL_RNG.instance

Can someone please explain what this does?


Anyone? I still could not figure out what this does.

I think it just executes the code inside the struct? I wasn’t aware that something like this was possible:

julia> struct Foo
           println("Hello world!")
Hello world!
1 Like

@rfourquet asked about it

but got no reply.

@jameson, sorry for the direct ping, but can you please explain this code in your PR? I am rather curious.

1 Like

It’s just the same as defining constructors, or whatever use you usually do:

struct A <: B
    A() = new()
    global copy() = new()
    x = 5

This answer surprised me more than the initial question (which I also had having looked at Random)

I did not know all these things are valid within a struct. What do they mean?

1 Like

You can basically write any code inside a struct definition. It’s just like a let clause or for loop, for example, in that it does introduce a new scope. That is why you need global if you want to use a variable outside the module definition. (The struct name is already global because the struct keyword creates a new constant global type, so you don’t need global for defining a default constructor.) The only difference if you are inside a struct definition is that you can use new to create a new instance of the struct. (FWIW you can use eval(Expr(:new, :T, x)) to create an instance of T with field x, like new does, even outside the struct definition, but that is definitely not something I’d recommend.)