go - 如何根据我发送给 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{} 当我测试一个元素个体时,它改变了类型,但它是整个数组仍然是 [] 接口{}
解决方案
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
}
推荐阅读
- vuetify.js - Vuetify Navigation Drawer 出现裁剪和抽屉大小的问题
- php - Symfony 5.1 - 在提交之前动态添加一个 CustomType 字段
- sqlite - 在 Flutter 应用程序中导入 sqlite 数据库文件
- mysql - 在 mysql 工作台中启动迁移向导时出现问题
- excel - 字符串在一个单元格中搜索多个值
- python - Discord bot 不从外部发送变量
- svg - 在 xaringan/remarkjs 中的“下一张幻灯片”事件中为 SVG 设置动画
- r - 将数据框组合在两个不同的列表中,以 R 中的元素名称为键
- delphi - Delphi TCustomTransparentControl 消失
- django - DoesNotExist at /my-cart/ 产品匹配查询不存在