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 关于#python#的问题:求帮写python代码
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?