我想得到v.val,但是 go 编译器给我一个错误:v.val 未定义(类型 testInterface 没有字段或方法 val)但是在v.testMe方法中,它可以工作。package mainimport ( "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)}
1 回答
至尊宝的传说
TA贡献1789条经验 获得超10个赞
您需要将界面转换回真实类型。请检查以下:
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)
}
- 1 回答
- 0 关注
- 182 浏览
添加回答
举报
0/150
提交
取消