douzhan2027 2018-12-21 02:18
浏览 53
已采纳

隐式转换应该何时成功失败? [重复]

This question already has an answer here:

I am super confused about this, I have:

func getKind(v interface{}) string {

    rt := reflect.TypeOf(v)
    switch rt.Kind() {
    case reflect.Slice:
        return "slice"
    case reflect.Array:
        return "array"
    default:
        return "unknown"
    }

}


func FlattenDeep(args ...interface{}) []interface{} {

    list := []interface{}{}

    for _, v := range args {

        kind := getKind(v)
        if kind != "unknown" {
            for _, z := range FlattenDeep((v.([]interface{}))...) {  // FAILS HERE
                list = append(list, z)
            }

        } else {
            list = append(list, v);
        }
    }
    return list;

}

the error is:

panic: interface conversion: interface {} is []func(http.HandlerFunc) http.HandlerFunc, not []interface {}

I don't understand, I thought a slice of anything could be converted to a slice of interface{}

I think I fixed the runtime error by doing this:

for _, v := range args {

    kind := getKind(v)
    if kind != "unknown" {

        a, ok := v.([]interface{})

        if ok == false {
           panic("o fuk")
        }

        for _, z := range FlattenDeep(a...) {
            list = append(list, z)
        }

    } else {
        list = append(list, v);
    }
}

still feels wrong tho, why Go? why

</div>
  • 写回答

1条回答 默认 最新

  • dousaoxiancy199896 2018-12-21 05:47
    关注

    The types are not equivalent, as stated in the comments.

    The operator you are attempting to use is called a "type assertion" not a "type conversion" for a reason. It does not manipulate the underlying data in any way. It merely asserts that the underlying data can be treated as if it were the asserted type (and in the single assignment form that you used, will panic if the type is incorrect).

    I'll skip the explanation of why this doesn't work and go directly to answering the following question

    Jesus, I thought at the very least slices/arrays could be generic, wtf am I supposed to do lol

    Define the following function:

    func toIfaceSlice(any interface{}) []interface{} {
        var out []interface{}
        rv := reflect.ValueOf(any)
        for i := 0; i < rv.Len(); i++ {
            out = append(out, rv.Index(i).Interface())
        }
        return out
    }
    

    Try on the Go Playground

    And use it to convert v before recursing into FlattenDeep.

    Note: for brevity, I left out any optimizations and error checking.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程