Golang中的"instanceof"等价物

Héc*_*tor 17 go

我有这个结构:

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)


Beh*_*nam 7

迟到的答案,但这工作正常

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

  • 如果要将接口与 float32 等基本类型进行比较,可以使用 ifreflect.TypeOf(objectPtr).Kind() ==reflect.Float32 {}`。示例:/sf/answers/3444486111/ (2认同)
  • @MewX 感谢重新创建了有用的 `IsInstanceof` 函数。我希望它能够激励 Golang 的创建者,并希望他们将其作为该语言的关键字。我猜他们只是忘了实施它。 (2认同)

Bil*_*win 5

TypeOf()方法返回一个类型为的对象Type,您可以使用该Name()方法以字符串的形式获取该类型的名称。

我还没有测试过,但是类似的东西可能起作用:

if reflect.TypeOf(event).Name() != "Like" {
Run Code Online (Sandbox Code Playgroud)

  • 我认为在@dave 的回答中使用 [type assertions](https://golang.org/ref/spec#Type_assertions) 更简单。 (2认同)

Boh*_*ian 5

最接近的翻译:

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