在下面的代码中,我正在尝试编写一个Txt()函数来打印出我的结构。它在完整代码中包含以下小问题:
完整代码:http://play.golang.org/p/nUsg_qbufP
type Char byte
type THeader struct {
Ver int8 // will show 1
Tag Char // will show 'H'
}
type TBody struct {
B1 [3]byte // will show "[0,0,0]"
B2 [4]Char // will show "ABCD"
}
func Txt(t interface{}) (s string) {
val := reflect.ValueOf(t)
typ := val.Type()
fields := typ.NumField()
for i := 0; i < fields; i++ {
sf := typ.Field(i)
valfld := val.Field(i)
vType := valfld.Type()
s += sf.Name + ":" + vType.String() + ":"
if strings.HasSuffix(vType.String(), "Char") {
if strings.HasPrefix(vType.String(), "[") {
v, ok := valfld.Interface().([4]Char)
s += fmt.Sprint(ok, v) + "\n"
} else {
s += fmt.Sprint(valfld.Interface()) + "\n"
}
} else {
s += fmt.Sprint(valfld.Interface()) + "\n"
}
}
return
}
func main() {
th := THeader{1, 'H'}
fmt.Printf("%#v\n", th)
// tb := TBody{B2: [10]Char("ABCD")}
tb := TBody{B2: [4]Char{'A', 'B', 'C', 'D'}}
fmt.Printf("%#v\n", tb)
fmt.Print("Txt(th):\n", Txt(th), "\n")
fmt.Print("Txt(tb):\n", Txt(tb), "\n")
}
答案 0 :(得分:1)
这个代码应该回答所有问题,除了你的第一个问题,这是不可能的,因为函数不能返回不同长度的数组,而Go无法初始化动态派生大小的数组。你需要切片。其余的代码可以使用idiomatic解决,使用Stringer接口并且不需要反射。
package main
import (
"fmt"
)
type Char byte
type CharSlice []Char
type ByteSlice []byte
func (s CharSlice) String() string {
ret := "\""
for _, b := range s {
ret += fmt.Sprintf("%c", b)
}
ret += "\""
return ret
}
func (s ByteSlice) String() string {
return fmt.Sprintf("%v", []byte(s))
}
type THeader struct {
Ver int8 // will show 1
Tag Char // will show 'H'
}
func (t THeader) String() string {
return fmt.Sprintf("{ Ver: %d, Tag: %c}", t.Ver, t.Tag)
}
type TBody struct {
B1 [3]byte // will show "[0,0,0]"
B2 [4]Char // will show "ABCD"
}
func (t TBody) String() string {
return fmt.Sprintf("{ B1: %s, B2: %s", ByteSlice(t.B1[:]), CharSlice(t.B2[:]))
}
func main() {
th := THeader{1, 'H'}
fmt.Printf("%#v\n", th)
tb := TBody{B2: [4]Char{'A', 'B', 'C', 'D'}}
fmt.Printf("%#v\n", tb)
fmt.Printf("Txt(th):\n%s\n", th)
fmt.Printf("Txt(tb):\n%s\n", tb)
}