This question already has an answer here:
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.
</div>
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