Go 语言编程 — 数据类型转换

目录

数据类型转换

类型转换用于将一种数据类型的变量转换为另外一种类型的变量。

格式:

type_name(expression)

[]byte => other type

注:[]byte 为字节流类型。

  • []byte => string
string([]byte)

int => other type

  • int => string
s = strconv.Itoa(i)
  • int => int32
i32 = int32(num)
  • int => int64
i64 = int64(num)
  • int64/int32 => int
i = int(num)
  • int64 => string
strconv.FormatInt(int64, 10)
  • int64 => time.Duration
time.Duration(int64)
  • int32 => byte
bytes.NewBuffer()
  • int => float64
float64(num) 
  • other type -> int
int(int32/int64)
int(int64/int32)

string => other type

  • string => int
strconv.Atoi(s)
  • string => bool
strconv.ParseBool("true")
  • string => float32
strconv.ParseFloat(s, 32)
  • string => float64
strconv.ParseFloat(s, 64)
  • string => uint
strconv.ParseUint()
  • string => int32/int64
strconv.ParseInt(s, 10, 32/64)
  • string(16进制) => int32/int64
strconv.ParseInt(s, 0, 32/64)
  • string => []byte
[]byte(string)

other type => string

  • int,int32,int64 => string
str1 := fmt.Sprintf("%d", i)            // int/int32/int64
str3 := strconv.FormatInt(int64(i), 10) // int/int32/int64
str2 := strconv.Itoa(i)                 // int
  • uint64 => string
strconv.FormatUint(unit64, 10)
  • bool => string
strconv.FormatBool(true)
  • float64 => string
strconv.FormatFloat(float64(12), 'f', -1, 64) 
fmt.Sprintf("%.2f", float64)

array => slice

copy(array[:], slice[0:4])
copy(array[:], slice)

for index, b := range someSlice {
	array[index] = b
}

猜你喜欢

转载自blog.csdn.net/Jmilk/article/details/107164554