golang最近挺火,試着用了一下,有些語法需要熟悉,記錄一下
常用數據格式
整型
uint8
、uint16
、uint32
、uint64
int8
、int16
、int32
、int64
浮點型
float32
、float64
字符串
string
格式轉換
strconv 包中常用的函數包括 Atoi()、Itia()、parse 系列函數、format 系列函數、append 系列函數等
string 與 int 的Atoi()、Itia()
num := strconv.Atoi(str)
str := strconv.Itoa(num)
string 轉其他格式的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 系列函數實現了將給定類型數據格式化爲字符串類型的功能,其中包括 FormatBool()、FormatInt()、FormatUint()、FormatFloat()。
str := strconv.FormatBool(num)
str := strconv.FormatInt(num, 16) // 16進制
str := strconv.FormatUint(num, 16) // 16進制
str := strconv.FormatFloat(num, 'f', 6, 64)
Append 系列函數用於將指定類型轉換成字符串後追加到一個切片中,其中包含 AppendBool()、AppendFloat()、AppendInt()、AppendUint()。
Append 系列函數和 Format 系列函數的使用方法類似,只不過是將轉換後的結果追加到一個切片中。
package main
import (
"fmt"
"strconv"
)
func main() {
// 聲明一個slice
b10 := []byte("int (base 10):")
// 將轉換爲10進制的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))
}