douyi1899 2018-03-14 06:02
浏览 198
已采纳

在golang中,为什么接口变量可以获取结构变量的地址,而不能从基本类型变量获取地址?

I am learning golang from "gotour" tool with "go1.10 darwin/amd64".

For below case:

package main

import "fmt"

type Myapi interface {
    fun1() int
}

type MyintA struct {
    val int
}

type MyintB int

func (v *MyintA)fun1() int {
    return int(v.val) + 1
}

func (v *MyintB)fun1() int {
    return int(*v) + 1
}

func main() {
    var a Myapi
    a = &MyintA{3}
    fmt.Println(a)
    a = &MyintB(2) // Need b:=MyintB(2); a=&b
    fmt.Println(a)
}

The compiling error is:

$ go run try.go

# command-line-arguments

./try.go:27:9: cannot take the address of MyintB(2)

Why the interface variable could get address directly from MyintA but not MyintB in this case?

  • 写回答

1条回答 默认 最新

  • duangai2831 2018-03-14 06:10
    关注

    It's explained in the specification:

    For an operand x of type T, the address operation &x generates a pointer of type *T to x. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a (possibly parenthesized) composite literal. If the evaluation of x would cause a run-time panic, then the evaluation of &x does too.

    The expression MyintB(2) is an constant value of type MyintB. It is not a variable or one of the other operands allowed in an address operation. Variables are declared with var or with a short variable declaration.

    The expression MyintA{3} is a composite literal. The exception to the addressability requirements allows taking the address of this operand.

    Do as the comment suggests to get a pointer to a MyintB:

    b := MyintB(2)
    a = &b
    

    The issue is with the address operator, not the assignment to an interface variable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line