2012-05-08 56 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)突出显示指针和结构赋值检查之间的区别 –

相关问题