英文:
Golang namespaces of namespaces
问题
我对Go语言还不太熟悉,但是从C++的背景来看,我确实想知道是否可以实现这样的功能。假设我有一个数学库,我想将一个命名空间作为另一个命名空间的子命名空间,就像这样:
- 主包
- 数学包
- 矩阵包
- ...
我希望以这样的方式调用我的代码:
math.matrix.CreateTranslation(mat4, 30, 50, 0)
在Go语言中是否有实现这种行为的方法?
英文:
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?
答案1
得分: 4
在Go语言中,无法直接实现这种行为。
你可以导入"module/math"
,然后使用math.SomeFunc
。或者你可以导入"module/math/matrix"
,然后使用matrix.SomeOtherFunc
。这些被称为"限定标识符"。
但是你不能导入"module/math"
或者"module/math/matrix"
,然后使用嵌套的"限定标识符",比如math.matrix.SomeOtherFunc
。这在Go语言的规范中并不支持。
从技术上讲,你可以尝试以下方式:
math.Matrix.CreateTranslation(mat4, 30, 50, 0)
其中,Matrix
是math
包中的一个导出的变量,它的类型要么具有CreateTranslation
方法,要么是一个具有名为CreateTranslation
的函数字段的结构体类型。
虽然从技术上讲是可能的,但显然这是试图在不支持此功能的语言上强行实现一种组织模式。
英文:
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论