如何转换为嵌套类型

huangapple go评论75阅读模式
英文:

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])
    }
}

huangapple
  • 本文由 发表于 2013年3月27日 08:07:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/15649739.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定