douwu0335 2019-08-13 11:28
浏览 101
已采纳

附加两个数组的泛型函数

Not able to figure out how to convert interface{} returned from function into an array of structs

As part of some practise i was trying to create a function which can take 2 slices of some type and concatenates both and returns the slice.

The code can be found here - https://play.golang.org/p/P9pfrf_qTS1

type mystruct struct {
    name  string
    value string
}

func appendarr(array1 interface{}, array2 interface{}) interface{} {
    p := reflect.ValueOf(array1)
    q := reflect.ValueOf(array2)
    r := reflect.AppendSlice(p, q)
    return reflect.ValueOf(r).Interface()
}

func main() {
    fmt.Println("=======")
    array1 := []mystruct{
        mystruct{"a1n1", "a1v1"},
        mystruct{"a1n2", "a1v2"},
    }
    array2 := []mystruct{
        mystruct{"a2n1", "a2v1"},
        mystruct{"a2n2", "a2v2"},
    }
    arrayOp := appendarr(array1, array2)
    fmt.Printf("arr: %#v
", arrayOp) // this shows all the elements from array1 and 2
    val := reflect.ValueOf(arrayOp)
    fmt.Println(val)                          // output is <[]main.mystruct Value>
    fmt.Println(val.Interface().([]mystruct)) // exception - interface {} is reflect.Value, not []main.mystruct
}

I may have slices of different types of structs. I want to concatenate them and access the elements individually. If there is any other way of achieving the same, please do let me know.

  • 写回答

1条回答 默认 最新

  • duangu1878 2019-08-13 11:34
    关注

    reflect.Append() returns a value of type reflect.Value, so you don't have to (you shouldn't) pass that to reflect.ValueOf().

    So simply change the return statement to:

    return r.Interface()
    

    With this it works and outputs (try it on the Go Playground):

    =======
    arr: []main.mystruct{main.mystruct{name:"a1n1", value:"a1v1"}, main.mystruct{name:"a1n2", value:"a1v2"}, main.mystruct{name:"a2n1", value:"a2v1"}, main.mystruct{name:"a2n2", value:"a2v2"}}
    [{a1n1 a1v1} {a1n2 a1v2} {a2n1 a2v1} {a2n2 a2v2}]
    [{a1n1 a1v1} {a1n2 a1v2} {a2n1 a2v1} {a2n2 a2v2}]
    

    You also don't need to do any reflection-kungfu on the result: it's your slice wrapped in interface{}. Wrapping it in reflect.Value and calling Value.Interface() on it is just a redundant cycle. You may simply do:

    arrayOp.([]mystruct)
    

    On a side note: you shouldn't create a "generic" append() function that uses reflection under the hood, as this functionality is available as a built-in function append(). The builtin function is generic, it gets help from the compiler so it provides the generic nature at compile-time. Whatever you come up with using reflection will be slower.

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

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)