我正致力于在 Go 中实现并发的 string
和 byte
阅读器。这样做的目的是允许解析 newline
和读取字符串中的其他此类字节。
在研究这个问题时,我发现了在单值上下文中处理多个值的各种方法 1 ,但是这些都没有处理混合类型的出现。有人建议使用接口(interface)来处理这个问题 2 ,并且已经尝试过,但我对现有建议的冗长冗长感到不舒服 3和 4 .
我想知道是否有一种惯用的方法可以以整洁的方式有效地对各种类型的值进行排序。
已编辑:首先,我按照建议建立了一个界面。这似乎是个好主意,如果我记得的话,这是 C 中常用的技巧。
func Use(vals ...interface{}) {
i := 0
p := []uint8{} //I've replaced the alias "byte" with the native "uint8"
var val uint8 //I've changed this declaration to a non-assigned declaration
for i, val := range vals {
if i < 1 {
_ = val
i++
} else {
p[i] = val.(uint8)
return fmt.Print(p[i]) //please excuse the earlier typo
//interestingly, this call to p[i] returns more than one value
}
}
}
其余的基本代码如下:
func other() (string, []byte) {
a := "declared and not used"
b := []byte("stuff")
return a,b
}
func main() {
Use(other())
}
我仍然不知道为什么这段代码在 p[i] 中应该有多个值。控制循环中使用的 空白标识符
不应该使这种可能性变得不太可能吗?
来自编辑代码的新错误报告为:
无效的类型断言:x.(uint8)(非接口(interface)类型 func(...interface {}) []interface {} 在左边)
原始代码可以在以下位置找到: https://play.golang.org/p/BEhOT7R0vvr
可以在以下位置找到编辑后的代码: https://goplay.space/#SF7X7dx8yL9
最佳答案
return fmt.print(p[i]) //interestingly, this call to p[i] returns more than one value
不,不是。
事实上,编译器不知道它返回了多少项,因为 fmt.printf
没有导出,所以它不知道它是什么。它只知道返回一个或多个 值。但是你在一个返回值为零的函数中,因此是错误的。
不清楚你想要什么,所以我不确定如何建议更改你的代码,但两个可能的答案似乎很明显:
停止返回:
fmt.Print(p[i]) return
更改您的函数以返回某些内容,然后调用正确的函数:
func Use(vals ...interface{}) byte { // ... skip return p[i]
关于go - 在 Go 中是否有一种惯用的方法来通过类型断言的接口(interface)进行索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58065841/