首页 > 解决方案 > 如何根据我发送给 Go 函数的变量返回特定类型的切片

问题描述

我有一个函数,它采用一个空接口(任何类型,我正在寻找特定的 2),然后返回所选类型的切片。

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
}

那么会发生什么,是 doc 变量确实改变了它的类型,但是当我返回切片时,它保持为 []interface{} 当我测试一个元素个体时,它改变了类型,但它是整个数组仍然是 [] 接口{}

标签: go

解决方案


tempArray问题中有你想要的切片。返回它而不是将值复制到[]interface{}您不想要的值。

使用此代码:

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
}

推荐阅读