golang-encoding模組學習

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
//Golang中encoding的用法package mainimport (       "bytes"       "encoding/binary"       "encoding/hex"       "encoding/xml"       "fmt"       "os")func goxml() {       type Address struct {              City, State string       }       //xml元素節點增加屬性,需要重新定製結構體       type ElementWithAttr struct{              AttrOne string `xml:"attrone,attr"`              AttrTwo string `xml:"attrtow,attr"`       }       type Person struct {              XMLName   xml.Name `xml:"person"`              Id        int     `xml:"id,attr"`              Sex       string  `xml:"sex,attr"`              FirstName string  `xml:"name>first"`              LastName  string  `xml:"name>last"`              Age       int     `xml:"age"`              Height    float32 `xml:"height,omitempty"`              EWA       ElementWithAttr `xml:elementwithattr`              //這裡寫子節點或者屬性的時候(凡是不是一個單獨字串),必須使用""來進行包封,否則反射的時候認不出來              EWAChild  string `xml:"elementwithattr>ewachild"`              Married   bool              Address              Comment string `xml:",comment"`       }       v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42, Sex:"Female"}       v.Comment = " Need more details. "       v.Address = Address{"Hanga Roa", "Easter Island"}       v.EWA = ElementWithAttr{"AttribteOne", "AttributeTwo"}       v.EWAChild = "ElementWithAttrChildNode"       enc := xml.NewEncoder(os.Stdout)       enc.Indent("  ", "    ")       if err := enc.Encode(v); err != nil {              fmt.Printf("error: %v\n", err)       }}func main() {       pi := 3.1415926       buf := bytes.Buffer{}       //使用的是小編碼,低地址對應低位元組       binary.Write(&buf, binary.LittleEndian, &pi)       //常量浮點數預設是float64       fmt.Printf("buf=%#v\n", buf.Bytes())       var rpi float64       binary.Read(&buf, binary.LittleEndian, &rpi)       fmt.Printf("rpi=%#v\n", rpi)       //和python的binascii庫的作用一樣,16進位和ascii字元之間的轉換       src := "Go is good language!我們都一樣"       //根據編碼後長度來分配緩衝空間       dst := make([]byte, hex.EncodedLen(len(src)))       hex.Encode(dst, []byte(src))       fmt.Printf("dst=%v\n", dst)       fmt.Printf("dst(hex)=%s\n", string(dst))       //根據解碼長度來分配緩衝空間       dst2 := make([]byte, hex.DecodedLen(len(dst)))       hex.Decode(dst2, dst)       fmt.Printf("dst2=%v\n", dst2)       fmt.Printf("dst2.(string)=%s\n", string(dst2))       goxml()}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.