gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:52:06 25 4
gpt4 key购买 nike

我正在使用“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)
}

编译错误为:

$ go run try.go

# command-line-arguments

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

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

最佳答案

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.

表达式MyintB(2)MyintB 类型的常量。它不是变量 或地址操作中允许的其他操作数之一。变量用 varshort variable declaration 声明.

表达式 MyintA{3} 是一个 composite literal .可寻址性要求的异常(exception)情况允许获取该操作数的地址。

按照评论的建议去做,得到一个指向 MyintB 的指针:

b := MyintB(2)
a = &b

问题出在地址运算符上,而不是接口(interface)变量的赋值。

关于go - 在 golang 中,为什么接口(interface)变量可以获取结构变量的地址但不能从基本类型变量获取地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49270700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com