小编bea*_*zyj的帖子

在Golang中,为什么接口变量可以获取struct变量的地址但不能从基本类型变量获取?

我正在使用"go1.10 darwin/amd64"从"gotour"工具学习golang.

对于以下情况:

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)
}
Run Code Online (Sandbox Code Playgroud)

编译错误是:

$ go run try.go

#command-line-arguments

./try.go:27:9:不能取MyintB的地址(2)

在这种情况下,为什么接口变量可以直接从MyintA获取地址而不是MyintB?

go

1
推荐指数
1
解决办法
598
查看次数

标签 统计

go ×1