douzhong5902 2019-07-30 19:37
浏览 149

如何根据我发送到Go中的函数的变量返回特定类型的切片

I have a function, that takes an empty interface (any type, which im looking for 2 in specific) and then returning a slice of the selected type.

func testingInterface(temp interface{}) (interface{}, interface{}) {
var doc interface{}

array := make([]interface{}, 3)

switch x := temp.(type) {
case int:
    doc = x
    tempArray := make([]string, 3)
    for i, v := range tempArray {
        array[i] = string(v)
    }
    fmt.Printf("Int to string %T, %T ", doc, tempArray)
case string:
    doc = x
    tempArray := make([]int, 3)

    for i, v := range tempArray {
        array[i] = int(v)
    }
    fmt.Printf("String to int %T, %T ", doc, tempArray)
}

  return array, doc
}

So what happens, it is that the doc variable indeed changes the type of it, but the slice when i return it, it stays as []interface{} When i test an element individual, it changes the type but the whole array it is still an []interface{}

  • 写回答

1条回答 默认 最新

  • doushan6692 2019-07-30 19:43
    关注

    The tempArray in the question has the slice you want. Return it instead of copying the values to the []interface{} that you don't want.

    Use this code:

    func testingInterface(x interface{}) (interface{}, interface{}) {
        var result interface{}
        switch x.(type) {
        case int:
            result = make([]int, 3)
        case string:
            result = make([]string, 3)
        }
        return result, x
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起