【问题标题】:Unable to access values from Pointer receiver无法从指针接收器访问值
【发布时间】:2019-03-29 06:25:51
【问题描述】:

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

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 值或错误。

【问题讨论】:

  • 这只是一个语法错误。如果myType 不是指针,则不能通过在其前面加上* 来取消引用它。如果要获取地址,则需要操作员& 的地址。再次参加围棋之旅,了解此类基础知识。
  • @Volker 你能介意指导我关于技术 1 吗?我没有使用指针引用,但仍然获取内存地址而不是值。
  • 你不是在写 Go 代码。如果你想调用一个函数,你必须用() 调用一个函数。你真的必须参加巡回赛。

标签: pointers go struct interface scheduler


【解决方案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>

【讨论】:

    【解决方案2】:

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

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

    正如 Volker 关于技术 3 所暗示的那样,您需要使用 &amp; 而不是 * 来获取对象的地址。

    【讨论】:

      猜你喜欢
      • 2015-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 2017-11-30
      相关资源
      最近更新 更多