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.