登录
首页 >  Golang >  Go问答

无法从指针接收器访问值

来源:stackoverflow

时间:2024-02-29 14:50:03 284浏览 收藏

golang学习网今天将给大家带来《无法从指针接收器访问值》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我无法从指针接收器获取值。它不断返回内存地址。

我正在尝试以下格式的其他文件中的指针接收器访问值

package types

import (
    // "Some product related imports"
    "golang.org/x/oauth2"
    "time"
)

type TestContext struct {
    userId string
}

func (cont *TestContext) GetUserId() string {
    return cont.userId
}

我试图通过多种方式解决这个问题,但要么获取内存地址、nil 值,要么出现错误。


解决方案


始终编写干净的代码:

  1. 名称为 userid,而不是 userid
  2. 名称为 userid(),而不是 getuserid()
  3. 使用 ctx2 := &mytype.mytype{} 而不是 ctx2 := *mytype.mytype{}

  4. 尝试 this 代码:

package main

import (
    "fmt"
)

type mytype struct {
    userid string
}

func (cont *mytype) userid() string {
    return cont.userid
}

func main() {
    ctx1 := mytype{"1"}
    fmt.println(ctx1.userid()) // 1

    ctx := mytype{"2"}
    var101 := ctx.userid()
    fmt.println(ctx1.userid(), var101) // 1 2

    ctx2 := &mytype{}
    fmt.println(ctx2) // &{}

    var ctx3 *mytype
    fmt.println(ctx3) // 
}

输出:

1
1 2
&{}

今天关于《无法从指针接收器访问值》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

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