整型

Go语言有固定长度的有符号和无符号整数类型:
  • int8, uint8
  • byte,是uint8的别名
  • int16, uint16
  • int32, uint32
  • rune, 是int32的别名
  • int64, uint64
还有依赖于CPU架构的整型:
  • int,在32为处理器上表示int32,在64位处理器上表示int64
  • uint,在32位处理器上是uint32,在64位处理器上是uint64
整数类型的零值是0。

strconv.Itoa 实现intstring

Go
Output
package main
import (
"fmt"
"strconv"
)
func main() {
var i1 int = -38
fmt.Printf("i1: %s\n", strconv.Itoa(i1))
var i2 int32 = 148
fmt.Printf("i2: %s\n", strconv.Itoa(int(i2)))
}
i1: -38
i2: 148

fmt.Sprintf实现intstring

Go
Output
package main
import (
"fmt"
)
func main() {
var i1 int = -38
s1 := fmt.Sprintf("%d", i1)
fmt.Printf("i1: %s\n", s1)
var i2 int32 = 148
s2 := fmt.Sprintf("%d", i2)
fmt.Printf("i2: %s\n", s2)
}
i1: -38
i2: 148

strconv.Atoi实现stringint

Go
Output
package main
import (
"fmt"
"log"
"strconv"
)
func main() {
s := "-48"
i1, err := strconv.Atoi(s)
if err != nil {
log.Fatalf("strconv.Atoi() failed with %s\n", err)
}
fmt.Printf("i1: %d\n", i1)
}
i1: -48

fmt.Sscanf实现stringint

Go
Output
package main
import (
"fmt"
"log"
)
func main() {
s := "348"
var i int
_, err := fmt.Sscanf(s, "%d", &i)
if err != nil {
log.Fatalf("fmt.Sscanf failed with '%s'\n", err)
}
fmt.Printf("i1: %d\n", i)
}
i1: 348

译者注

strconv是处理字符串转换的标准库,它是 string convert 的缩写,Itoa意为 Int to A,int表示整型,A为第一个英文字母泛指字符(串)。