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?
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.