douji0073 2019-01-22 07:59
浏览 496
已采纳

如何将切片转换为数组?

I want to implement a method to convert a interface{} slice to a interface{} array which has equal length to the given slice. It's similar to below:

func SliceToArray(in []interface{}) (out interface{}) {
 ...
}
// out's type is [...]interface{} and len(out)==len(in)

How can I implement this method?

EDIT: Any possible to use reflect.ArrayOf to implement this?

  • 写回答

1条回答 默认 最新

  • dqkf36241 2019-01-22 19:13
    关注

    Use reflect.ArrayOf to create the array type given the slice element type. Use reflect.New to create a value of that type. Use reflect.Copy to copy from the slice to the array.

    func SliceToArray(in interface{}) interface{} {
        s := reflect.ValueOf(in)
        if s.Kind() != reflect.Slice {
            panic("not a slice")
        }
        t := reflect.ArrayOf(s.Len(), s.Type().Elem())
        a := reflect.New(t).Elem()
        reflect.Copy(a, s)
        return a.Interface()
    }
    

    Run it on the Playground

    This function is useful for creating a map key from a slice and other scenarios where a comparable value is required. Otherwise, it's usually best to use a slice when the length can be arbitrary.

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

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的算法代码
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据