登录
首页 >  Golang >  Go问答

利用类型断言检索切片元素

来源:stackoverflow

时间:2024-03-18 11:27:30 368浏览 收藏

**文章首段摘要:** 本文探讨了一种使用类型断言检索接口切片元素的方法。该方法通过比较对象类型的字符串表示来查找匹配项,但存在性能影响和类型断言带来的乏味问题。文章建议使用反射包来直接匹配两个接口,并提供了一个使用引用参数作为结果占位符的替代解决方案,可以避免性能冲击和类型断言的复杂性。

问题内容

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

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)

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


解决方案


到目前为止 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

本篇关于《利用类型断言检索切片元素》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>