-1

Please see the below code

import (
    ...
    "context"
    ...
)

type myStruct struct {
    ID  string
    Sig string
}

mySig := myStruct{
    ID:  "12345678",
    Sig: "Secret_Signature_Token",
}

// Setting a Value associated with a Key in Context
_ := context.WithValue(ctx, "myKey", &mySig)           -- 1

//Getting the same value
value, ok := ctx.Value("myKey").(*myStruct)            -- 2

Now, my question is: what is the use/meaning of .(*myStruct) in the above expression number 2 Could someone please explain the statement number 2 step by step.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Nitin Soni
  • 15
  • 1
  • 4

1 Answers1

4

ctx.Value("myKey") returns an interface. So .(*myStruct) does a type assertion to convert it to the type *myStruct. So the value on the left hand side is of type *myStruct and you can access its fields e.g. value.ID.

A version of your example can be seen here: https://play.golang.org/p/Eg0v3vuSi6y

Satyajit Das
  • 2,740
  • 5
  • 16
  • 30