golang常用格式轉(zhuǎn)換語法

golang最近挺火,試著用了一下,有些語法需要熟悉,記錄一下

常用數(shù)據(jù)格式

整型
uint8、uint16uint32、uint64
int8、int16、int32、int64
浮點(diǎn)型
float32、float64
字符串
string

格式轉(zhuǎn)換

strconv 包中常用的函數(shù)包括 Atoi()、Itia()、parse 系列函數(shù)、format 系列函數(shù)、append 系列函數(shù)等

string 與 int 的Atoi()、Itia()

num := strconv.Atoi(str)
str := strconv.Itoa(num)

string 轉(zhuǎn)其他格式的ParseBool()、ParseFloat()、ParseInt()、ParseUint()

boo1, err := strconv.ParseBool(str1)
num, err := strconv.ParseInt(str, 10, 0)
num, err := strconv.ParseUint(str, 10, 0)
num, err := strconv.ParseFloat(str, 64)

Format 系列函數(shù)實(shí)現(xiàn)了將給定類型數(shù)據(jù)格式化為字符串類型的功能,其中包括 FormatBool()、FormatInt()、FormatUint()、FormatFloat()。

str := strconv.FormatBool(num)
str := strconv.FormatInt(num, 16)  // 16進(jìn)制
str := strconv.FormatUint(num, 16)  // 16進(jìn)制
str := strconv.FormatFloat(num, 'f', 6, 64) 

Append 系列函數(shù)用于將指定類型轉(zhuǎn)換成字符串后追加到一個(gè)切片中,其中包含 AppendBool()、AppendFloat()、AppendInt()、AppendUint()。
Append 系列函數(shù)和 Format 系列函數(shù)的使用方法類似,只不過是將轉(zhuǎn)換后的結(jié)果追加到一個(gè)切片中。

package main
import (
    "fmt"
    "strconv"
)
func main() {
    // 聲明一個(gè)slice
    b10 := []byte("int (base 10):")
  
    // 將轉(zhuǎn)換為10進(jìn)制的string,追加到slice中
    b10 = strconv.AppendInt(b10, -42, 10)
    fmt.Println(string(b10))
    b16 := []byte("int (base 16):")
    b16 = strconv.AppendInt(b16, -42, 16)
    fmt.Println(string(b16))
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容