无法从指针接收器访问值

问题描述 投票:-4回答:2

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

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
}

在其他文件中,我正在使用它

package abc

import (
    myType "xyz_path/types"
)

func getAllUsersConn() map[string]interface{} {

    // Technique 1
    // Below commands working fine and returning memory address
    ctx1 := myType.TestContext{}
    logging.Debug("Here 3 = ", ctx1.GetUserId())

    // above working fine but with address

    // Technique 2

    // Below return will nill values
    ctx := myType.TestContext{}
    var101 := (ctx.GetUserId())
    logging.Debug(ctx, var101)

    // Technique 3

    // Below returns with error : invalid indirect of types.TestContext literal (type types.TestContext)
    ctx2 := *myType.TestContext{} // Error : invalid indirect of types.TestContext literal (type types.TestContext)
    // and if
    ctx2 := *myType.TestContext // ERROR : type *types.TestContext is not an expression
    logging.Debug("exp id = ", ctx2.GetUserId)

    UsersConn := make(map[string]interface{})
    // passing some hardcoded values for test, but need to get the user id from above then pass
    return UsersConn
}

我试图通过多种方式解决它,但要么获取内存地址,nil值或错误。

pointers go struct interface scheduler
2个回答
1
投票

总是写清洁代码:

  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) // <nil>
}

输出:

1
1 2
&{}
<nil>

-1
投票

对于技术1.我不确定logging.Debug()是做什么的,但我认为你正在尝试将字符串传递给它。在这种情况下使用ctx2.GetUserId()而不是ctx2.GetUserId。我知道这听起来很傻但是要调用一个不带参数的函数你还需要括号。

主要问题是您正在使用myType包,但您认为您正在使用类型包。否则我认为技术2会好的。

而Volker暗示tehcnique 3你需要使用&而不是*来获取一个物体的地址。

© www.soinside.com 2019 - 2024. All rights reserved.