我想获得 v.val ,但go编译器会给我一个错误:
v.val undefined(类型testInterface没有字段或方法val)
但是在 v.testMe 方法中,它可以正常工作。
package main
import (
"fmt"
)
type testInterface interface {
testMe()
}
type oriValue struct {
val int
}
func (o oriValue) testMe() {
fmt.Println(o.val, "I'm test interface")
}
func main() {
var v testInterface = &oriValue{
val: 1,
}
//It work!
//print 1 "I'm test interface"
v.testMe()
//error:v.val undefined (type testInterface has no field or method val)
fmt.Println(v.val)
}
答案 0 :(得分:0)
您需要将界面转换回真实类型。请查看以下内容:
package main
import (
"fmt"
)
type testInterface interface {
testMe()
}
type oriValue struct {
val int
}
func (o oriValue) testMe() {
fmt.Println(o.val, "I'm test interface")
}
func main() {
var v testInterface = &oriValue{
val: 1,
}
//It work!
//print 1 "I'm test interface"
v.testMe()
//error:v.val undefined (type testInterface has no field or method val)
fmt.Println(v.(*oriValue).val)
}