josesnchz
josesnchz

Reputation: 73

Calling type function for a member of map

I'm coding a communication protocol. It sends tokens, which I need to use to authenticate. I have created a type, "AuthToken" that encodes/decodes the token for me.

In the package "utils", I declare it and some of the functions like this (this is like a pseudo-code):

package utils

type AuthToken struct{
   // vars
}

func (token *AuthToken) Decode(encoded string){
   // Decodes the token and fills internal fields
}

func (token AuthToken) GetField() string{
   return field
}

In my main package, I want to create a map of AuthTokens to store them, but I can't use the function Decode in a member of the map, while I can use GetField:

package main

type TokenList map[string]utils.AuthToken

func main(){
   tokenList := make(TokenList)
   // To init one member I do:
   tokenList["1"] = utils.AuthToken{} // This works
   tokenList["2"] = make(utils.AuthToken) // This doesn't
   // Then I need to call the function above, so I tried:
   tokenList["1"].Decode("encoded") // Returns cannot call pointer method

I have tried searching for it, but either I don't know where to search, or there is no info about how to do this.

Upvotes: 1

Views: 27

Answers (1)

novalagung
novalagung

Reputation: 11532

tokenList["2"] = make(utils.AuthToken) // This doesn't

You cannot use make keyword to instantiate an object from struct. That's the reason why above statement wont work.


tokenList["1"] = utils.AuthToken{}
tokenList["1"].Decode("encoded") // Returns cannot call pointer method

The tokenList["1"] returns non pointer object. You will need to store it into a variable, then from there do access the pointer, only then you will be able to call .Decode() method.

obj := tokenList["1"]
objPointer := &obj
objPointer.Decode("encoded")

Upvotes: 1

Related Questions