2013-04-08 74 views
2

在下面的代碼中,我試圖編寫一個Txt()函數來打印出我的結構。它包含以下的完整代碼小問題:如何漂亮地打印字節數組和字符數組?

  1. 如何寫一行通過字符串初始化字符數組(47行)
  2. 如何加快檢查char類型無弦函數(線29,30)
  3. 如何打印出字符陣列串(第32行)
  4. 如何打印出字符字符串,也許用sprintf(「%C」),但它是非常緩慢的。(第34行)

完整代碼在: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

「漂亮」包 - https://github.com/kr/pretty - 可能會給你一些有用的想法。 – 2013-04-08 03:45:00

+0

如果您使用切片而不是數組([] Char而不是[4] Char),則一切都會更容易。我假設你希望通過使用數組來獲得性能? – 2013-04-08 06:51:02

+0

我已經介紹了漂亮的代碼。我使用[4] Char而不是[] Char,因爲我想讀取網絡流,它需要特定的固定大小才能使用binary.Read()。 – 2013-04-08 07:21:09

回答

1

此代碼應該回答一切除了你第1'的問題,因爲函數無法返回不同長度的陣列和Go有沒有工廠初始化動態派生大小的數組這是不可能的。你需要切片。剩下的代碼可以通過使用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) 

} 
+0

除非你不關心unicode,否則應該輸入「Char rune」。 – OneOfOne 2014-06-18 13:36:58