英文:
How to convert to nested type
问题
我已经定义了两种类型
type zFrame []byte
type zMsg []zFrame
并且我有一个变量
var message [][]byte
。当我尝试编译
myZMsg := zMsg(message)
时,Go编译器告诉我
cannot use msg (type [][]byte) as type zMsg in function argument
。将其改为
type zMsg [][]byte
可以编译通过,但我更喜欢第一种解决方案。有没有一种简单的方法可以将[][]byte
转换为zMsg
?
英文:
I've defined the two types
type zFrame []byte
type zMsg []zFrame
and I have the variable
var message [][]byte
. Go compiler is telling me
cannot use msg (type [][]byte) as type zMsg in function argument
when I try to compile
myZMsg := zMsg(message)
. Changing to
type zMsg [][]byte
makes things compile, but I like the first solution better. Is there an easy way for me to convert from [][]byte
to zMsg
for that case?
答案1
得分: 4
你将不得不自己进行转换。例如,
package main
type zFrame []byte
type zMsg []zFrame
func main() {
var message [][]byte
myZMsg := make(zMsg, len(message))
for i := range message {
myZMsg[i] = zFrame(message[i])
}
}
英文:
You'll have to do the conversion yourself. For example,
package main
type zFrame []byte
type zMsg []zFrame
func main() {
var message [][]byte
myZMsg := make(zMsg, len(message))
for i := range message {
myZMsg[i] = zFrame(message[i])
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论