2016-05-20 37 views
0

獲得屬性我想要得到的v.val,但去編譯扔我一個錯誤:如何從interfce例如,從結構圍棋

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

回答

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

+0

非常感謝那是救我的天! – user1458435