I'm trying to decode dynamic structures from network data, here is simplified version. The FmtA
is [3]byte
, and required to print as string. So, here is my stupid implementation by defining a Bytes3
data type.
If use this method, I should define Bytes6
, Bytes4
, Bytes2
.
Is there any better method to print all byte arrays as strings instead of byte arrays?
package main
import "fmt"
type Bytes3 [3]byte
type FmtA struct {
Field1 Bytes3
Field2 [6]byte
Field3 uint8
}
type FmtB struct {
Field1 uint16
Field2 [4]byte
Field3 [2]byte
}
func (b Bytes3) String() string {
v := [3]byte(b)
return string(v[:])
}
func main() {
a := FmtA{[3]byte{'a', 'b', 'c'}, [6]byte{'d', 'e', 'f', 'g', 'h', 'i'},
36}
b := FmtB{42, [4]byte{'a', 'b', 'c', 'd'}, [2]byte{'e', 'f'}}
var i interface{} // simulate the received variable type
i = a
fmt.Printf("a=%+v
", i)
i = b
fmt.Printf("b=%+v
", i)
// Output:
// a={Field1:abc Field2:[100 101 102 103 104 105] Field3:36}
// b={Field1:42 Field2:[97 98 99 100] Field3:[101 102]}
}