【问题标题】:Pattern to lookup a slice element by an injected type通过注入类型查找切片元素的模式
【发布时间】:2019-01-12 15:22:27
【问题描述】:

我尝试使用对象的类型在接口切片中查找对象。我目前的解决方案如下:

package main

import (
    "errors"
    "fmt"
)

type Entity struct {
    children []Childable
}

func (e *Entity) ChildByInterface(l interface{}) (Childable, error) {
    for _, c := range e.children {
        if fmt.Sprintf("%T", c) == fmt.Sprintf("%T", l) {
            return c, nil
        }
    }
    return nil, errors.New("child doesn't exist")
}

type Childable interface {
    GetName() string
}

func main() {
    ent := &Entity{
        []Childable{
            &Apple{name: "Appy"},
            &Orange{name: "Orry"},
            // more types can by introduced based on build tags
        },
    }

    appy, err := ent.ChildByInterface(&Apple{})
    if err != nil {
        fmt.Println(err)
    } else {
        appy.(*Apple).IsRed()
        fmt.Printf("%+v", appy)
    }
}

type Apple struct {
    name string
    red  bool
}

func (a *Apple) GetName() string {
    return a.name
}

func (a *Apple) IsRed() {
    a.red = true
}

type Orange struct {
    name   string
    yellow bool
}

func (o *Orange) GetName() string {
    return o.name
}

func (o *Orange) IsYellow() {
    o.yellow = true
}

https://play.golang.org/p/FmkWILBqqA-

可以使用构建标签注入更多 Childable 类型(Apple、Orange 等)。因此,为了保证查找类型的安全并避免错误,我将interface{} 传递给查找函数。 Childable 接口还确保新注入的类型实现正确的功能。

这就是事情开始变得混乱的地方。目前我正在对接口的类型和 Childable 对象的类型进行字符串比较,以查看它们是否匹配: fmt.Sprintf("%T", c) == fmt.Sprintf("%T", l)

那我还是只能返回 Childable 接口。所以我必须使用类型断言来获得正确的类型:appy.(*Apple)

为了让子项具有正确的类型而进行的锅炉电镀变得非常乏味,而字符串比较以找到匹配项对性能产生了重大影响。我可以使用什么更好的解决方案来匹配两个接口以避免性能冲击?

【问题讨论】:

  • 接口的使用方式是需要键入断言值以获取基础类型。你想达到什么目标?
  • 在返回值上应用显式类型断言是这样做的方法。当您依赖运行时信息来执行实现时,您将始终受到“性能”影响。这可能与您正在寻找的类型相等测试 github.com/mh-cbon/service-finder/blob/master/… 接近
  • 使用Is("red") 之类的东西并在两个对象上调用Is 函数不是更好吗?
  • @danicheeta 我刚刚添加了 IsRed 和 IsYellow 函数来表明这两个结构应该能够具有不同的方法(因此需要类型断言)。根据您的建议,我意识到它们的效率很低。

标签: go interface type-assertion


【解决方案1】:

fmt.Sprintf("%T", c) 在后台使用reflect 而言,暗示它没有任何优势- 最好直接使用reflect。 您可以使用引用参数作为结果的占位符而不是返回值。

func (e *Entity) ChildByInterface(l Childable) error {
    for _, c := range e.children {
        if reflect.TypeOf(l) == reflect.TypeOf(c) {
            fmt.Println(c)
            reflect.ValueOf(l).Elem().Set(reflect.ValueOf(c).Elem())
            return nil
        }
    }
    return errors.New("child doesn't exist")
}

现在传递一个占位符

apple := &Apple{}
err := ent.ChildByInterface(apple)
//and use it
apple.IsRed()

Working code

【讨论】:

  • @Himanshu 该接口允许通过新的构建标签引入其他结构,并仍然确保它“实现” Childable 接口。
  • @FanusduToit 很适合提出这个问题。请编辑您的问题并添加此要求,这将很有帮助。
  • @Uvelichitel 您使用的以下行不会导致实质上克隆值而不是将指针返回到原始值吗? reflect.ValueOf(l).Elem().Set(reflect.ValueOf(c).Elem())
  • 它用从c取消引用的值填充l指向的地址
  • 是的,所以如果我的理解正确,这个apple := &Apple{} 的内存地址不会和这个&Apple{name: "Appy"} 的地址相同,因为前者会分配额外的内存只是为了这个切片查找。是不是有点过分了?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-31
  • 1970-01-01
  • 2016-03-15
  • 1970-01-01
  • 2021-10-22
  • 2021-11-01
相关资源
最近更新 更多