Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pointers 无法从指针接收器访问值_Pointers_Go_Struct_Interface_Scheduler - Fatal编程技术网

Pointers 无法从指针接收器访问值

Pointers 无法从指针接收器访问值,pointers,go,struct,interface,scheduler,Pointers,Go,Struct,Interface,Scheduler,我无法从指针接收器获取值。它不断返回内存地址。 我正试图以下面的格式从其他文件访问指针接收器中的值 package types import ( // "Some product related imports" "golang.org/x/oauth2" "time" ) type TestContext struct { userId string } func (cont *TestConte

我无法从指针接收器获取值。它不断返回内存地址。
我正试图以下面的格式从其他文件访问指针接收器中的值

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。我不确定logging.Debug()的作用,但我认为您正在尝试向它传递字符串。在这种情况下,请使用
ctx2.GetUserId()
而不是
ctx2.GetUserId
。我知道这听起来很傻,但是调用一个不带参数的函数仍然需要括号

主要问题是您使用的是myType包,但您认为您使用的是types包。否则我认为技术2就可以了


正如沃尔克在Tecnique 3中暗示的那样,您需要使用
&
而不是
*
来获取对象的地址。

始终编写干净的代码:

  • 名称
    userID
    不是
    userID
  • 名称
    UserID()
    不是
    GetUserId()
  • 使用
    ctx2:=&myType.myType{}
    代替
    ctx2:=*myType.myType{}

  • 试用代码:

  • 主程序包
    进口(
    “fmt”
    )
    类型myType结构{
    用户标识字符串
    }
    func(cont*myType)UserID()字符串{
    返回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)//&{}
    变量ctx3*myType
    fmt.Println(ctx3)//
    }
    
    输出:

    1
    1 2
    &{}
    <nil>
    
    1
    1 2
    &{}
    
    这只是一个语法错误。如果
    myType
    不是指针,则不能通过在它前面加
    *
    来取消对它的引用。如果要获取地址,需要操作员的地址
    &
    。对于这类基础知识,请再次参加围棋之旅。@Volker你能给我介绍一下技巧1吗?我没有使用指针引用,但仍然得到内存地址而不是值。您没有编写Go代码。如果要调用函数,必须使用
    ()
    调用函数。你真的必须参加围棋之旅。
    1
    1 2
    &{}
    <nil>