douyi1899
douyi1899
2018-03-14 06:02

在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 duangai2831 3年前

    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.

    点赞 评论 复制链接分享

相关推荐