#Questions about memory

15 messages · Page 1 of 1 (latest)

ancient osprey
#

So lets say I have an function that returns a pointer struct object (the addr of the struct object).

Example struct:


type (
  user struct {
      email string
      ctx context.Context
  }
)

Its a weird example I know. But my question is, when i make a method for this struct type that creates and returns an pointer touser (return &newUser). Does this mean that in my memory there is a user object holded which contains email and ctx. Because user is a pointer to the struct the values i change overtime maybe with newer methods are automatically manipulating the user object right

#

func (u *user) ChangeMail(newmail string){
    u.email = newmail
}
#

but the real question is when a user makes a context and provides it to set on the user struct trough a supported method like above, how does the defer cancel() work on the context, he passes a copy of a context but after he passes it in the struct ctx itself its known but outside not really..


type (
    user struct {
        email string
        ctx context.Context
    }
)

func (u *user) ChangeMail(newmail string){
    u.email = newmail
}

func (u *user) SetContext(ctx context.Context){
    u.ctx = ctx
}

func Newuser(mail string, ctx context.Context) *user{
    return &user{email: mail, ctx: ctx}
}

func main(){
    ctx, cancel := context.WithTimeout(context.Background(), time.Second * 1)
    defer cancel()
    
    newuser := Newuser("[email protected]", ctx)
    newuser.ChangeMail("[email protected]")
}
#

how is it possible that defer cancel() works, because its literally a copy of ctx when i pass it into newuser method, its not the real referrence

#

or are context types working different than normal idk

modest night
#

The type context.Context is an interface. It being a pointer or a value depends on the concrete implementation.

#

The underlying type here is &timerCtx, which is a pointer.

#

And no, context types are just types. They are not magic in any way.

#

Vanishingly few things in Go are special cases treated separately.

ancient osprey
#

@modest night ty for explaining !

#

i understand it now

#

@modest night ben je nl🤣?

modest night
ancient osprey
#

i though u were dutch so i asked in dutch if u were dutch.

i though like so bcs ur name means demons in dutch @modest night