golangstruct to buf自留笔记
/** * Created with IntelliJ IDEA. * User: liaojIE * Date: 13-7-4 * Time: 下午1:42 * To change this template use file | Settings | file Templates. */package mainimport ( "bytes" "enCoding/binary" "reflect" "io" "errors" "fmt")func writeBuf(w io.Writer,v reflect.Value) (n int,err error){ newBuf := bytes.NewBuffer(nil) for i := 0; i < v.NumFIEld(); i++ { switch v.FIEld(i).Type().Kind() { case reflect.Struct: n,err := writeBuf(newBuf,v.FIEld(i)) if err != nil { return n,err } case reflect.Bool: boolByte := []byte{0} if v.FIEld(i).Bool() { boolByte = []byte{1} } newBuf.Write(boolByte) case reflect.String: newBuf.WriteString(v.FIEld(i).String()) case reflect.Slice: newBuf.Write(v.FIEld(i).Bytes()) case reflect.Int: binary.Write(newBuf,binary.littleEndian,int32(v.FIEld(i).Int())) case reflect.Uint: binary.Write(newBuf,uint32(v.FIEld(i).Uint())) case reflect.Uint8,reflect.Uint16,reflect.Uint32,reflect.Uint64,reflect.Int8,reflect.Int16,reflect.Int32,reflect.Int64,reflect.float32,reflect.float64,reflect.Complex64,reflect.Complex128: binary.Write(newBuf,v.FIEld(i).Interface()) } } return w.Write(newBuf.Bytes())}func WriteStructToBuffer(w io.Writer,data interface{}) ( error ) { v := reflect.Indirect(reflect.ValueOf(data)) if v.Kind() == reflect.Struct { fmt.Println("test") _,err := writeBuf(w,v) return err } return errors.New("invalID type Not a struct")}func StringFixedLength(s string,length int) []byte { sLength := len(s) if sLength >= length { return []byte(s[:length]) } else { b := make([]byte,length-sLength) return append([]byte(s),b...) } return nil}总结
以上是内存溢出为你收集整理的GO语言-struct to buf全部内容,希望文章能够帮你解决GO语言-struct to buf所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)