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


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 {

    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?


Solution 1:

Add Set function for BaseRepository

Solution 2:

use unsafe package

type BaseRepository struct {
    database string

type PointRepository struct {
    pointCollection string

baseRepository := &internel.BaseRepository{}
databasePointer := (*string)(unsafe.Pointer(uintptr(unsafe.Pointer(baseRepository))))
*databasePointer = "changed here"


&{database:changed here}

This is just an example, you should change the type of the field database.

Answered By – Inasa Xia

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.