0

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

v.val 未定义(类型 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)
}
4

1 回答 1

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

检查去游乐场

于 2016-05-20T10:10:44.237 回答