int转string
package main
import (
"fmt"
"strconv"
)
func main() {
var i int = 10
// 通过Itoa方法转换
str1 := strconv.Itoa(i)
// 通过Sprintf方法转换
str2 := fmt.Sprintf("%d", i)
// 打印str1
fmt.Println(str1)
// 打印str2
fmt.Println(str2)
}
string转uint16
numStr := "123"
num16, _ := strconv.ParseUint(numStr, 10, 16)
num16=uint16(num16)
string 转uint
var v = "3"
id, _ := strconv.ParseUint(v, 10, 64)
numUint := uint(id)
float转string
f:=1.545757
fStr:=strconv.FormatFloat(f,'f',-1,32)
fmt.Println(fStr)//==>1.545757
byte和int相互转换
package main
import (
"bytes"
"encoding/binary"
"fmt"
)
func IntToBytes(n int) []byte {
data := int64(n)
bytebuf := bytes.NewBuffer([]byte{})
binary.Write(bytebuf, binary.BigEndian, data)
return bytebuf.Bytes()
}
func BytesToInt(bys []byte) int {
bytebuff := bytes.NewBuffer(bys)
var data int64
binary.Read(bytebuff, binary.BigEndian, &data)
return int(data)
}
func main() {
fmt.Println(IntToBytes(1))
fmt.Println(BytesToInt(IntToBytes(1)))
}
[]byte中的元素转int
首先[]byte中的元素本身就是uint8类型的,下图的encodeData是一个 [ ]byte类型的数组,所以
a:=int(encodeData[i])
interface{} 转为普通类型
p, ok := t.(bool)
p, ok := t.(int64)
interface{}类型转结构体类型
场景:这种转换我觉得主要用在一个方法的参数是interface{}类型的时候
可以再想想Java的多态
type A struct {
Name string
}
type B struct {
Age int
}
func TypeChange(model interface{}) error {
switch model.(type) { //通过类型断言来判断类型
case A:
realModel, ok := model.(A)//类型转换
if ok {
fmt.Println(realModel.Name)
}
break
case B:
realModel, ok := model.(B)
if ok {
fmt.Println(realModel.Age)
}
break
}
return nil
}
数组转字符串
str:=strings.Replace(strings.Trim(fmt.Sprint(data), "[]"), " ", ",", -1)
string 转bool
//It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False.
//Any other value returns an error.
strconv.ParseBool(abnormityTypeStr)