duandun3178 2015-03-13 20:35
浏览 32

是否有惯用的方式对golang片进行“插入” [重复]

I would like to check if a value is in a slice of values. What is the best way to achieve this? Something like the following:

if "foo" in []string{"foo", "bar"}...

I've written the following code but not sure how idiomatic it is (golang newbie):

// Convert a slice or array of a specific type to array of interface{}
func ToIntf(s interface{}) []interface{} {
    v := reflect.ValueOf(s)
    // There is no need to check, we want to panic if it's not slice or array
    intf := make([]interface{}, v.Len())
    for i := 0; i < v.Len(); i++ {
        intf[i] = v.Index(i).Interface()
    }
    return intf
}
func In(s []interface{}, val interface{}) bool {
    for _, v := range s {
        if v == val {
            return true
        }
    }
    return false
}

So, to use this, here is a test method I wrote.

func TestIn(t *testing.T) {
    s := []string{"foo", "bar", "kuku", "kiki"}
    for _, v := range s {
        if !In(ToIntf(s), v) {
            t.Error("Should be in")
        }
    }
    if In(ToIntf(s), "foobar") {
        t.Error("Should not be in")
    }
}
</div>
  • 写回答

2条回答 默认 最新

  • dongyong3554 2015-03-13 20:50
    关注

    The idiomatic way, in go, for functions that can be expressed with a simple loop, to be implemented that way. Your method, for example, could be written that way:

    for _, value := range slice {
        if value == var {
            doSomething()
        }
    }
    

    Obviously, it is somewhat more verbose, but that only if you try to translate language or choice here in go.

    The downside of doing reflection is that you botch performances without being that simpler than if you write your code to integrate to the search rather than simply considering it a condition.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题