英文:
Is there a way to access an internal parameter in a custom constructor from struct in Go?
问题
我想访问自定义构造函数中的内部属性,对我来说,它是来自超类的属性,就像这样:
type BaseRepository struct {
database mongo.Database
}
type PointRepository struct {
BaseRepository
pointCollection mongo.Collection
}
func NewPointRepository() *PointRepository {
pointCollection := ***self***.database.GetCollection("points")
pr := &PointRepository{
pointCollection: pointCollection,
}
}
如你所见,我需要访问类似 self 的东西才能使这种方法起作用。
我该如何解决这个问题?
英文:
I would like to access an internal property in a custom constructor, in my case it's a property from a superclass, like this:
type BaseRepository struct {
database mongo.Database
}
type PointRepository struct {
BaseRepository
pointCollection mongo.Collection
}
func NewPointRepository() *PointRepository {
pointCollection := ***self***.database.GetCollection("points")
pr := &PointRepository{
pointCollection: pointpointCollection,
}
}
As you can see, I need to access something like self to this approach works.
How can I workaround this situation?
答案1
得分: 2
在Go语言中没有构造函数或类。
PointRepository
嵌入了BaseRepository
,而BaseRepository
有一个未导出的database
字段。在与BaseRepository
相同的包中的任何函数都可以直接访问database
字段。
如果你需要从包外的函数访问该字段,你要么需要将其导出,要么在BaseRepository
中提供一个导出的getter方法。
英文:
There are no constructors or classes in Go.
PointRepository
embeds BaseRepository
, which has an unexported database
field. Any function in the same package as BaseRepository
can directly access the database
field.
If you need to access that field from a function outside the package, you either have to export it, or you have to provide an exported getter method in BaseRepository
.
答案2
得分: 0
解决方案1:
> 为 BaseRepository
添加 Set
函数
解决方案2:
> 使用 unsafe
包
type BaseRepository struct {
database string
}
type PointRepository struct {
BaseRepository
pointCollection string
}
baseRepository := &internel.BaseRepository{}
databasePointer := (*string)(unsafe.Pointer(uintptr(unsafe.Pointer(baseRepository))))
*databasePointer = "changed here"
fmt.Printf("%+v",baseRepository)
输出:
&{database:changed here}
这只是一个示例,你应该根据实际情况更改字段 database 的类型。
英文:
Solution 1:
> Add Set
function for BaseRepository
Solution 2:
> use unsafe
package
type BaseRepository struct {
database string
}
type PointRepository struct {
BaseRepository
pointCollection string
}
baseRepository := &internel.BaseRepository{}
databasePointer := (*string)(unsafe.Pointer(uintptr(unsafe.Pointer(baseRepository))))
*databasePointer = "changed here"
fmt.Printf("%+v",baseRepository)
output:
&{database:changed here}
This is just an example, you should change the type of the field database.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论