Go語言類型轉換

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

摘自快樂編程 » golang類型轉換

 

golang是強型別語言,在應用過程中類型轉換基本都會用到。下面整理一下常用的類型轉換,會持續更新。

整形轉字串

fmt.Println(strconv.Itoa(100))

該方法的源碼是:

// Itoa is shorthand for FormatInt(i, 10).
func Itoa(i int) string {
        return FormatInt(int64(i), 10)
}

可以看出是FormatInt方法的簡單實現。

字串轉整形

i, _ := strconv.Atoi("100")
fmt.Println(i)

64位整形轉字串

var i int64
i = 0x100
fmt.Println(strconv.FormatInt(i, 10))

FormatInt第二個參數表示進位,10表示十進位。

位元組轉32位整形

b := []byte{0x00, 0x00, 0x03, 0xe8}
bytesBuffer := bytes.NewBuffer(b)

var x int32
binary.Read(bytesBuffer, binary.BigEndian, &x)
fmt.Println(x)

其中binary.BigEndian表示位元組序,相應的還有little endian。通俗的說法叫大端、小端。

32位整形轉位元組

var x int32
x = 106
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, x)
fmt.Println(bytesBuffer.Bytes())

位元組轉字串

fmt.Println(string([]byte{97, 98, 99, 100}))

字串轉位元組

fmt.Println([]byte("abcd"))

   

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.