I want to get the v.val , but the go compiler throw me an Error:
v.val undefined (type testInterface has no field or method val)
but in the v.testMe method,It work.
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)
}
You need to convert back your interface to the real type. Please check below :
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)
}
Check on Go Playground
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.