Home > OS >  Is there a way to access an internal parameter in a custom constructor from struct in Go?
Is there a way to access an internal parameter in a custom constructor from struct in Go?

Time:02-27

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?

CodePudding user response:

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.

CodePudding user response:

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.

  • Related