A complete guide to converting Golang characters to integers

WBOY
Release: 2024-04-03 11:48:01
Original
537 people have browsed it

In the Go language, methods for converting characters to integers include: using the strconv.Atoi function to convert strings to integers. Use the strconv.ParseInt function to convert a string to an integer in the specified base. Represents a single Unicode character using a Unicode literal and converts it to an integer.

A complete guide to converting Golang characters to integers

Complete guide to converting Go language characters to integers

In the Go language, the character type (rune) can represent Unicode characters , while integer types (int, int8, etc.) represent numeric values. Therefore, in some cases, characters need to be converted to integers.

String to integer

Atoi

##strconv.Atoi The function converts a string to an integer.

import (
    "fmt"
    "strconv"
)

func main() {
    str := "1234"
    n, err := strconv.Atoi(str)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Int:", n)
    }
}
Copy after login

Output:

Int: 1234
Copy after login

ParseInt

strconv.ParseInt Function converts a string to an integer in the specified base.

n, err := strconv.ParseInt(str, 10, 64) // 10 为十进制基数,64 为位数
Copy after login

Convert a single character to an integer

Use Unicode literal value

Unicode literal value can represent a single Unicode character.

r := '1'
n := int(r - '0')
Copy after login

Practical Case

When processing user input or parsing other data, it is common to need to convert characters into integers. For example:

Read integers from the command line

fmt.Println("请输入一个整数:")
var n int
fmt.Scan(&n) // 从 stdin 读入并解析为整数
Copy after login

Process JSON data

type Data struct {
    Age int `json:"age"`
}

json.Unmarshal(data, &d) // JSON 数据反序列化为结构体
Copy after login

Parse file path

path := "path/to/file.txt"
size := path[len(path)-5:] // 获取文件大小部分
n, err := strconv.Atoi(size)
Copy after login

The above is the detailed content of A complete guide to converting Golang characters to integers. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!