我有这个结构:
type Event interface {
Accept(EventVisitor)
}
type Like struct {
}
func (l *Like) Accept(visitor EventVisitor) {
visitor.visitLike(l)
}
Run Code Online (Sandbox Code Playgroud)
我该如何测试这event是一个Like实例?
func TestEventCreation(t *testing.T) {
event, err := New(0)
if err != nil {
t.Error(err)
}
if reflect.TypeOf(event) != Like {
t.Error("Assertion error")
}
}
Run Code Online (Sandbox Code Playgroud)
我明白了:
类型Like不是表达式事件事件
dav*_*ave 31
你可以投出它,看它是否失败:
event, err := New(0)
if err != nil {
t.Error(err)
}
_, ok := event.(Like)
if !ok {
t.Error("Assertion error")
}
Run Code Online (Sandbox Code Playgroud)
迟到的答案,但这工作正常
package main
import (
"fmt"
"reflect"
)
type SomeStruct1 struct{}
type SomeStruct2 struct{}
func IsInstanceOf(objectPtr, typePtr interface{}) bool {
return reflect.TypeOf(objectPtr) == reflect.TypeOf(typePtr)
}
func main() {
//sample variables
someString := "Some String"
someFloat := float32(2.4)
someStruct1 := SomeStruct1{}
someStruct2 := SomeStruct2{}
someStruct1Ptr := &SomeStruct1{}
// primitive string
fmt.Println("string <-> *string \t\t", IsInstanceOf(someString, (*string)(nil))) //false
fmt.Println("*string <-> *string \t\t", IsInstanceOf(&someString, (*string)(nil))) //true
// primitive float32
fmt.Println("float32 <-> *float32 \t\t", IsInstanceOf(someFloat, (*float32)(nil))) //false
fmt.Println("*float32 <-> *float32 \t\t", IsInstanceOf(&someFloat, (*float32)(nil))) //true
// structure
fmt.Println("SomeStruct1 <-> *SomeStruct1 \t", IsInstanceOf(someStruct1, (*SomeStruct1)(nil))) //false
fmt.Println("*SomeStruct1 <-> *SomeStruct1 \t", IsInstanceOf(&someStruct1, (*SomeStruct1)(nil))) //true
fmt.Println("*SomeStruct2 <-> *SomeStruct1 \t", IsInstanceOf(&someStruct2, (*SomeStruct1)(nil))) //false
fmt.Println("*SomeStruct1 <-> *SomeStruct1 \t", IsInstanceOf(someStruct1Ptr, (*SomeStruct1)(nil))) //true
}
Run Code Online (Sandbox Code Playgroud)
游乐场(在线运行):https : //play.golang.org/p/tcQqdzUGMlL
该TypeOf()方法返回一个类型为的对象Type,您可以使用该Name()方法以字符串的形式获取该类型的名称。
我还没有测试过,但是类似的东西可能起作用:
if reflect.TypeOf(event).Name() != "Like" {
Run Code Online (Sandbox Code Playgroud)
最接近的翻译:
// java
if (x instanceof y) {
// x is a y
}
Run Code Online (Sandbox Code Playgroud)
是:
// go
if _, ok := x.(y); ok {
// x is a y
}
Run Code Online (Sandbox Code Playgroud)