Integers
suggest changeGo has fixed-size signed and unsigned integers:
int8
,uint8
byte
is an alias foruint8
int16
,uint16
int32
,uint32
rune
is an alias forint32
int64
,uint64
It also has architecture-dependent integers:
int
isint32
on 32-bit processors andint64
on 64-bit processorsuint
isuint32
on 32-bit processors anduint64
on 64-bit processors
Zero value of an integer is 0.
Convert int to string with strconv.Itoa
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
Convert int to string with fmt.Sprintf
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
Convert string to int with strconv.Atoi
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
Convert string to int with fmt.Sscanf
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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents