如何从Go中的struct的interfce实例获取属性

时间:2016-05-20 09:44:50

标签: go go-interface

我想获得 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)
}

1 个答案:

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

检查Go Playground