Golang 中的类型映射? [英] Map of types in Golang?

查看:28
本文介绍了Golang 中的类型映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为音频/视频流编写一个解析器,它已知由几种特定类型的帧组成.每个帧类型都有自己的子标题格式,因此我为每个帧类型定义了一个结构类型,以便将它们用于作为第三个参数传递给 binary.Read:

I am writing a parser for audio/video stream which is known to be comprised of frames of several certain types. Each frame type has its own subheader format, so I define a struct type for each to use them for variables passed as the 3rd argument to binary.Read:

type TypeVideoIHeader struct {
    MType       byte // type of media e.g. H.264
    FPS         byte
    Width       byte
    Height      byte
    DateTime    int32
    Length      int32
}

type TypeVideoPHeader struct {
    Length      int32
}

type TypeAudioHeader struct {
    MType       byte
    SampleRate  byte
    Length      int16
}

帧是哪种类型是由其标头中的某个字节定义的,因此我将它们放入常量中:

Which type a frame is is defined by a certain byte in its header, so I put those into constants:

type FrameType byte

const (
    VideoI  FrameType = 0xFC
    VideoP  FrameType = 0xFD
    Audio   FrameType = 0xFA
)

现在,在我可以调用 binary.Read 之前 我必须创建一个正确类型的变量(上面的 3 个结构之一),函数将填充它来自流的值.

Now, before I can call binary.Read I have to create a variable of the right type (one of the 3 structs above) which the function will fill with values from the stream.

如何仅通过 FrameType 变量初始化正确类型的变量?有没有简洁优雅的解决方案?

How do I initialise a variable of the right type just by a FrameType variable? Is there a concise and elegant solution?

说这种技巧是否可行:

TMap := map[FrameType]type{
    VideoI: TypeVideoIHeader,
    VideoP: TypeVideoPHeader,
    Audio: TypeAudioHeader,
}

var videoISubHeader TMap[VideoI]

——这就是我所追求的.

— that would be sort of what I am after.

推荐答案

TMap := map[FrameType]func() interface{} {
    VideoI: func() interface{} { return &TypeVideoIHeader{} },
    VideoP: func() interface{} { return &TypeVideoPHeader{} },
    Audio:  func() interface{} { return &TypeAudioHeader{} },
}

var videoISubHeader = TMap[VideoI]()

if err := binary.Read(r, order, videoISubHeader); err != nil {
    panic(err)
}

注意 binary.Read 期望第三个参数是一个指针,否则它将无法将二进制数据读入传入的变量中,这就是函数使用 &.

Note that binary.Read expects the 3rd argument to be a pointer, else it won't be able to read the binary data into the passed in variable, which is why the functions use &.

这篇关于Golang 中的类型映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆