Home >Backend Development >Golang >Learn the type conversion function in Go language and implement the function of converting string to integer
Learn the type conversion function in Go language and implement the function of converting string to integer
In Go language, type conversion is the process of converting one data type to another data type. Go language provides type conversion functions to achieve conversion between different types.
This article will learn the type conversion function in Go and the sample code to realize the function of converting string to integer.
The strconv package of the Go language provides many functions for type conversion. Among them, the Atoi() function is used to convert strings to integers. The following is the declaration and usage example of the Atoi() function:
func Atoi(s string) (int, error)
The parameter of the Atoi() function is a string s, and the return value is the converted integer and an error. If the conversion is successful, the converted integer value and nil are returned; if the conversion fails, 0 and an error are returned.
Sample code:
package main import ( "fmt" "strconv" ) func main() { str := "12345" num, err := strconv.Atoi(str) if err != nil { fmt.Println("字符串转整数失败:", err) return } fmt.Println("转换后的整数:", num) }
Run the above code, the output result will be:
转换后的整数:12345
In addition to using the Atoi() function of the strconv package, we can also customize functions to convert strings to integers.
Sample code:
package main import ( "fmt" ) func StringToInt(str string) (int, error) { var num int for i := 0; i < len(str); i++ { if str[i] >= '0' && str[i] <= '9' { num = num*10 + int(str[i]-'0') } else { return 0, fmt.Errorf("字符串中包含非数字字符") } } return num, nil } func main() { str := "12345" num, err := StringToInt(str) if err != nil { fmt.Println("字符串转整数失败:", err) return } fmt.Println("转换后的整数:", num) }
Run the above code, the output result is also:
转换后的整数:12345
The above is to learn the type conversion function in Go language and realize the function of converting string to integer methods and sample code. Hope this article is helpful to you!
The above is the detailed content of Learn the type conversion function in Go language and implement the function of converting string to integer. For more information, please follow other related articles on the PHP Chinese website!