Golang strconv.Atoi()函数及示例
Go语言通过strconv包提供了内置支持,可以实现基本数据类型的字符串表示形式与字符串之间的转换。该包提供了一个 Atoi()函数 ,它相当于ParseInt(str string, base int, bitSize int),用于将字符串类型转换为整数类型。要访问 Atoi()函数 ,您需要在程序中导入strconv包。
Syntax:
func Atoi(str string) (int, error)
这里的str是字符串。
示例1:
// Golang program to illustrate
// strconv.Atoi() function
package main
import (
"fmt"
"strconv"
)
func main() {
// Using Atoi() function
x := "245"
y, e := strconv.Atoi(x)
if e == nil {
fmt.Printf("%T \n %v", y, y)
}
}
输出:
int
245
示例2:
// Golang program to illustrate
// strconv.Atoi() function
package main
import (
"fmt"
"strconv"
)
func main() {
// Using Atoi() function
x1 := "245"
fmt.Println("Before:")
fmt.Printf("Type: %T ", x1)
fmt.Printf("\nValue: %v", x1)
y1, e1 := strconv.Atoi(x1)
if e1 == nil {
fmt.Println("\nAfter:")
fmt.Printf("Type: %T ", y1)
fmt.Printf("\nValue: %v", y1)
}
x2 := "1"
fmt.Println("\n\nBefore:")
fmt.Printf("Type: %T ", x2)
fmt.Printf("\nValue: %v", x2)
y2, e2 := strconv.Atoi(x2)
if e2 == nil {
fmt.Println("\nAfter:")
fmt.Printf("Type: %T ", y2)
fmt.Printf("\nValue: %v", y2)
}
}
输出:
Before:
Type: string
Value: 245
After:
Type: int
Value: 245
Before:
Type: string
Value: 1
After:
Type: int
Value: 1