国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development Golang How to convert string to int type in go language

How to convert string to int type in go language

Mar 15, 2021 pm 02:00 PM
go language type conversion

Conversion method: 1. Use the Atoi() function in the strconv package to convert the integer of the string type into the int type, with the syntax "strconv.Atoi(string)"; 2. Use the Atoi() function in the strconv package The ParseInt() function can return an integer value represented by a string (accepting positive and negative signs), and the syntax is "strconv.ParseInt(string,10,64)".

How to convert string to int type in go language

The operating environment of this tutorial: windows10 system, GO 1.18, thinkpad t480 computer.

How to convert strings to various int types in golang

Convert string to int:

int, err := strconv.Atoi(string)

string to int64:

int64, err := strconv.ParseInt(string, 10, 64)

int to string:

string := strconv.Itoa(int)

int64 to string:

string := strconv.FormatInt(int64,10)

Go language strconv (type conversion) Introduction

The strconv package in Go language implements mutual conversion between basic data types and their string representations.

strconv package

The strconv package implements the conversion of basic data types and their string representations. It mainly has the following common functions: Atoi (), Itia(), parse series, format series, append series.

Please check the official documentation for more functions.

String and int type conversion

This set of functions is the most commonly used in our daily programming.

Atoi()

Atoi() function is used to convert the string type integer to the int type , The function signature is as follows.

func Atoi(s string) (i int, err error)

If the incoming string parameter cannot be converted to int type, an error will be returned.

s1 := "100"
i1, err := strconv.Atoi(s1)
if err != nil {
    fmt.Println("can't convert to int")
} else {
    fmt.Printf("type:%T value:%#v\n", i1, i1) //type:int value:100
}

Itoa()

Itoa() function is used to convert int type data into the corresponding string means, the specific function signature is as follows.

func Itoa(i int) string

The sample code is as follows:

i2 := 200s2 := strconv.Itoa(i2)fmt.Printf("type:%T value:%#v\n", s2, s2) //type:string value:"200"

Parse series function

Parse class function is used to convert a string to a given Values ??of type: ParseBool(), ParseFloat(), ParseInt(), ParseUint().

ParseBool()

func ParseBool(str string) (value bool, err error)

Returns the bool value represented by a string. It accepts 1, 0, t, f, T, F, true, false, True, False, TRUE, FALSE; otherwise it returns an error.

ParseInt()

func ParseInt(s string, base int, bitSize int) (i int64, err error)

Returns an integer value represented by a string, accepting positive and negative signs.

base specifies the base (2 to 36). If base is 0, it will be judged from the prefix of the string. "0x" is hexadecimal, "0" is octal, otherwise it is decimal. System;

bitSize specifies the integer type that the result must be assigned without overflow, 0, 8, 16, 32, and 64 respectively represent int, int8, int16, int32, and int64;

The err returned It is of type *NumErr. If the syntax is incorrect, err.Error = ErrSyntax; if the result exceeds the type range, err.Error = ErrRange.

ParseUnit()

func ParseUint(s string, base int, bitSize int) (n uint64, err error)

ParseUintSimilar to ParseInt but does not accept signs, used for unsigned integers .

ParseFloat()

func ParseFloat(s string, bitSize int) (f float64, err error)

Parse a string representing a floating point number and return its value.

If s conforms to the grammatical rules, the function will return a floating point number closest to the value represented by s (using IEEE754 standard rounding).

bitSize specifies the expected receiving type, 32 is float32 (the return value can be assigned to float32 without changing the exact value), 64 is float64;

The return value err is of *NumErr type, If the syntax is incorrect, err.Error=ErrSyntax; if the result exceeds the representation range, the return value f is ±Inf, and err.Error=ErrRange.

Code example

b, err := strconv.ParseBool("true")
f, err := strconv.ParseFloat("3.1415", 64)
i, err := strconv.ParseInt("-2", 10, 64)
u, err := strconv.ParseUint("2", 10, 64)

These functions have two return values. The first return value is the converted value, and the second return value is the converted value. error message.

Format series functions

The Format series functions implement the function of formatting a given type of data into string type data.

FormatBool()

func FormatBool(b bool) string

Returns "true" or "false" according to the value of b.

FormatInt()

func FormatInt(i int64, base int) string

Returns the base base string representation of i. base must be between 2 and 36, and lowercase letters 'a' to 'z' will be used in the result to represent numbers greater than 10.

FormatUint()

func FormatUint(i uint64, base int) string

is the unsigned integer version of FormatInt.

FormatFloat()

func FormatFloat(f float64, fmt byte, prec, bitSize int) string

The function represents a floating point number as a string and returns it.

bitSize represents the source type of f (32: float32, 64: float64), and will be rounded accordingly.

fmt representation format: 'f' (-ddd.dddd), 'b' (-ddddp±ddd, exponent is binary), 'e' (-d.dddde±dd, decimal exponent), ' E' (-d.ddddE±dd, decimal exponent), 'g' (use 'e' format when the exponent is very large, otherwise 'f' format), 'G' (use 'E' format when the exponent is very large, otherwise 'f' format).

prec controls precision (excluding the exponent part): for 'f', 'e', ??'E', it represents the number of digits after the decimal point; for 'g', 'G', it controls the total Number of digits. If prec is -1, it means using the minimum number of numbers necessary to represent f.

Code Example

s1 := strconv.FormatBool(true)
s2 := strconv.FormatFloat(3.1415, 'E', -1, 64)
s3 := strconv.FormatInt(-2, 16)
s4 := strconv.FormatUint(2, 16)

其他

isPrint()

func IsPrint(r rune) bool

返回一個(gè)字符是否是可打印的,和unicode.IsPrint一樣,r必須是:字母(廣義)、數(shù)字、標(biāo)點(diǎn)、符號、ASCII空格。

CanBackquote()

func CanBackquote(s string) bool

返回字符串s是否可以不被修改的表示為一個(gè)單行的、沒有空格和tab之外控制字符的反引號字符串。

其他

除上文列出的函數(shù)外,strconv包中還有Append系列、Quote系列等函數(shù)。具體用法可查看官方文檔。

推薦學(xué)習(xí):Golang教程

The above is the detailed content of How to convert string to int type in go language. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. ?...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Do I need to install an Oracle client when connecting to an Oracle database using Go? Do I need to install an Oracle client when connecting to an Oracle database using Go? Apr 02, 2025 pm 03:48 PM

Do I need to install an Oracle client when connecting to an Oracle database using Go? When developing in Go, connecting to Oracle databases is a common requirement...

In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? Apr 02, 2025 pm 05:03 PM

Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...

Is the Go language interface a duck type? What is the implementation mechanism of polymorphism? Is the Go language interface a duck type? What is the implementation mechanism of polymorphism? Apr 02, 2025 pm 02:48 PM

Interfaces and polymorphism in Go: Clarifying common misunderstandings Many Go beginners often connect the concepts of "duck type" and "polymorphism" with Go...

Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

See all articles