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
)
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.
How do I initialise a variable of the right type just by a FrameType
variable? Is there a concise and elegant solution?
Say if this kind of trick was possible:
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)
}
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 &
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.