Go 类型转换
go 类型转换
string int int64
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main
import (
"fmt"
"strconv"
)
func main() {
var str string
fmt.Printf("str type:%T\n", str)
str = "123"
var strInt int
// string > int
strInt, _ = strconv.Atoi(str)
fmt.Println(str, strInt)
var strInt64 int64
// string > int64
strInt64, _ = strconv.ParseInt(str, 10, 64)
fmt.Println(strInt64)
var intStr int
intStr = 100
// int > string
intToString := strconv.Itoa(intStr)
fmt.Println(intToString)
// int64 > string
int64ToStr := strconv.FormatInt(strInt64, 10)
fmt.Println(int64ToStr)
}
整形互转
整形之间互转
int64(int)
需要转什么类型就括号外面什么类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main
import "fmt"
func main() {
var int1 int
int1 = 21
var int2 int64
// int > int64
int2 = int64(int1)
fmt.Println(int2)
var inta int64
inta = 10
var intb int
// int64 > int64
intb = int(inta)
fmt.Println(intb)
u := uint32(int1)
fmt.Println(u)
}
bool To string
1
2
3
4
5
6
7
8
9
10
11
12
package main
import (
"fmt"
"strconv"
)
func main() {
var b bool
formatBool := strconv.FormatBool(b)
fmt.Println(formatBool)
}
fmt.Sprintf
To string
1
2
3
4
5
6
7
8
9
10
package main
import "fmt"
func main() {
var byteType byte
var str string
str = fmt.Sprintf("整型 %d 浮点 %f byte %c %s", 1, 3.14, byteType, "字符串拼接")
fmt.Println(str)
}
This post is licensed under
CC BY 4.0
by the author.