登录
首页 >  Golang >  Go问答

执行针对Map成员的类型函数调用

来源:stackoverflow

时间:2024-02-09 19:33:24 156浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《执行针对Map成员的类型函数调用》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我正在编写一个通信协议。它发送令牌,我需要用它来进行身份验证。 我创建了一个类型“authtoken”,它为我编码/解码令牌。

在包“utils”中,我声明了它和一些像这样的函数(这就像伪代码):

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
}

在我的主包中,我想创建一个 authtokens 映射来存储它们,但我无法在映射成员中使用 decode 函数,但可以使用 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

我尝试过搜索它,但要么我不知道在哪里搜索,要么没有关于如何执行此操作的信息。


正确答案


tokenlist["2"] = make(utils.authtoken) // this doesn't

您不能使用 make 关键字从结构体实例化对象。这就是为什么上面的语句不起作用的原因。

tokenlist["1"] = utils.authtoken{}
tokenlist["1"].decode("encoded") // returns cannot call pointer method

tokenlist["1"] 返回非指针对象。您需要将其存储到一个变量中,然后从那里访问指针,然后您才能调用 .decode() 方法。

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

本篇关于《执行针对Map成员的类型函数调用》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>