如何从 Go 中的结构中的接口实例获取属性

How to get attribute from a interfce instance from struct in Go

我想得到 v.val,但是 go 编译器给我一个错误:

v.val undefined (type testInterface has no field or method 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)
}

您需要将接口转换回真实类型。请检查以下内容:

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)
}

检查Go Playground