Golang namespaces of namespaces


I’m kinda new to go and from being a C++ background I really wonder if its possible to achieve something like this. Let’s say I have a math library and i want to make a namespace a children of another namespace like this.

  • main package
  • math package
    • matrix package

And I want to call my code like this ;

math.matrix.CreateTranslation(mat4, 30, 50, 0)

Is there a way to achieve this kind of behaviour in go?


Is there a way to achieve this kind of behaviour in go?

No, not really.

You can import "module/math" and then do math.SomeFunc. Or you can import "module/math/matrix" and then do matrix.SomeOtherFunc. These are referred to as "qualified identifiers".

But you cannot import "module/math" or "module/math/matrix" and then use a nested "qualified identifier" a la math.matrix.SomeOtherFunc. It’s just not part of the spec.

Technically speaking it is possible to do the following:

math.Matrix.CreateTranslation(mat4, 30, 50, 0)

where Matrix is an exported variable in the math package and whose type either has a CreateTranslation method in its method set, or whose type is a struct type that has a function field called CreateTranslation.

While possible, it would, obviously, be an attempt to force an organizational pattern on a language that does not support it.

Answered By – mkopriva

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.