2012-05-08 60 views
10

如何確保類型在編譯時實現接口?這樣做的典型方法是通過未能分配支持該類型的接口,但是我有幾種只能動態轉換的類型。在運行時,這會產生非常粗糙的錯誤消息,而沒有針對編譯時錯誤給出更好的診斷。在運行時發現我期望支持接口的類型也很不方便,事實上並非如此。確保類型在編譯時在Go中實現接口

+0

在什麼語言? – EJP

+0

@EJP:應該是_go_,谷歌語言 – themarcuz

回答

10

假設問題與Go有關,例如

var _ foo.RequiredInterface = myType{} // or &myType{} or [&]myType if scalar 

作爲頂級域名將在編譯時檢查。

編輯:S/[*]/&/

EDIT2:S /虛擬/ _ /,由於凌動

+4

你可以寫'_'而不是'dummy'。 – 2012-05-08 14:22:34

+1

我很喜歡你的sed風格的編輯符號。 – Matt

1

像這樣:

http://play.golang.org/p/57Vq0z1hq0

package main 

import(
    "fmt" 
) 

type Test int 

func(t *Test) SayHello() { 
    fmt.Println("Hello"); 
} 

type Saluter interface{ 
    SayHello() 
    SayBye() 
} 

func main() { 
    t := Saluter(new(Test)) 
    t.SayHello() 
} 

將產生:

prog.go:19: cannot convert new(Test) (type *Test) to type Saluter: 
    *Test does not implement Saluter (missing SayBye method) 
-3

我不喜歡通過在主代碼中放置虛擬行來產生編譯器拋出錯誤的想法。這是一個很有效的解決方案,但我更願意爲此寫一個測試。

假設我們有:

type Intfc interface { Func() } 
type Typ int 
func (t Typ) Func() {} 

此測試確保Typ實現Intfc

package main 

import (
    "reflect" 
    "testing" 
) 

func TestTypes(t *testing.T) { 
    var interfaces struct { 
     intfc Intfc 
    } 
    var typ Typ 
    v := reflect.ValueOf(interfaces) 
    testType(t, reflect.TypeOf(typ), v.Field(0).Type()) 
} 

// testType checks if type t1 implements interface t2 
func testType(t *testing.T, t1, t2 reflect.Type) { 
    if !t1.Implements(t2) { 
     t.Errorf("%v does not implement %v", t1, t2) 
    } 
} 

您可以將它們添加到TestTypes功能檢查所有的類型和接口。爲Go編寫測試介紹here

+1

呃,沒有。爲避免編譯器的靜態類型檢查而使用反射編寫測試用例是不可取的。 – zzzz

+0

這是怎麼回事? – Mostafa

+1

Go是一種靜態類型的語言。靜態類型檢查有什麼問題?如果靜態類型檢查是不可能的,動態類型檢查是合理的,恕我直言。 – zzzz

-1
package main 

import (
    "fmt" 
) 

type Sayer interface { 
    Say() 
} 

type Person struct { 
    Name string 
} 

func(this *Person) Say() { 
    fmt.Println("I am", this.Name) 
} 

func main() { 
    person := &Person{"polaris"} 

    Test(person) 
} 

func Test(i interface{}) { 
    //!!here ,judge i implement Sayer 
    if sayer, ok := i.(Sayer); ok { 
     sayer.Say() 
    } 
} 

的代碼示例是在這裏:http://play.golang.org/p/22bgbYVV6q

2

在圍棋的語言中沒有 「工具」 聲明的設計。要求編譯器通過嘗試賦值來檢查類型T是否實現接口I的唯一方法(是的,一個虛擬的:)。注意,Go lang區分在結構和指針上聲明的方法,在分配檢查中使用正確的

type T struct{} 
var _ I = T{}  // Verify that T implements I. 
var _ I = (*T)(nil) // Verify that *T implements I. 

閱讀常見問題的詳細信息Why doesn't Go have "implements" declarations?

+0

[http://play.golang.org/p/UNXt7MlmX8](http://play.golang。org/p/UNXt7MlmX8)突出顯示指針和結構賦值檢查之間的區別 –

相關問題