go 基本类型的互转

转转转,类型转换是静态语言(强类型语言)在代码时候经常要进行的动作。这篇文章是我 golang 开发中类型转换的一些笔记。interface、struct、map相关的转换参考前文《golang 解析 map[string]interface{} 和 json 到 struct》

package xxx

import (
    "strconv"
)

int -> string

// int64
var Int64 int64 = 9223372036854775807
str := strconv.FormatInt(Int64, 10)

// unit64
var Uint64 uint64 = 18446744073709551615
str2 := strconv.FormatUint(Uint64, 10)

// int32
var test int32 = xxx
str3 := strconv.Itoa(int(test)) 

// int32 
// 对比: <https://stackoverflow.com/questions/39442167/convert-int32-to-string-in-golang>

s = String(i)                       takes:  5.5923198s
s = String2(i)                      takes:  5.5923199s
s = strconv.FormatInt(int64(i), 10) takes:  5.9133382s
s = strconv.Itoa(int(i))            takes:  5.9763418s
s = fmt.Sprint(i)                   takes: 13.5697761s

string -> int

// int64
var strInt64 string = "9223372036854775807"
convertedStrInt64, _ := strconv.ParseInt(strInt64, 10, 64)

// uint64
var strUint64 string = "18446744073709551615"
convertedStrUint64, _ := strconv.ParseUint(strUint64, 10, 64)

interface -> map[string] interface

// data 为 interface
data.(map[string]interface{})

interface -> string

// data 为 interface
data.(string)

string->[]byte

var str string = "test"
data := []byte(str)

[]byte->string

var data [10]byte 
string := string(data)

参考资料


将 Kubernetes unstructured 类型转为对象 go 使用 ast 优化结构体打印样式