Home  >  Article  >  Backend Development  >  Learn Golang character conversion from scratch

Learn Golang character conversion from scratch

王林
王林Original
2024-04-03 13:21:01652browse

在 Go 中,字符转整型可通过 strconv.Atoi() 函数实现。其语法为 func Atoi(s string) (int, error),其中 s 为要转换的字符串,转换后的整型为 int,若转换失败则返回 error。实战案例包括将数字字符转换和非数字字符转换,其中非数字字符转换会返回 strconv.ErrSyntax 错误。此外,传递给 strconv.Atoi 函数的字符串不能为空,否则也会返回 strconv.ErrSyntax 错误。

Learn Golang character conversion from scratch

从零开始学习 Go 语言:字符转整型

在 Go 语言中,字符(rune)和整型(int)是不同的数据类型。有时,需要将字符转换为整型,本文将介绍如何在 Go 中完成这一操作。

语法

func Atoi(s string) (int, error)
  • s 是要转换的字符串。
  • int 是转换后的整型。
  • error 是如果转换失败,则返回的错误。

实战案例

将数字字符转换为整型

import (
    "fmt"
    "strconv"
)

func main() {
    s := "42"
    i, err := strconv.Atoi(s)
    if err != nil {
        // 转换失败,处理错误
    }
    
    fmt.Println(i + 10) // 输出 52
}

将非数字字符串转换为整型

如果字符串不是有效的数字,Atoi 函数会返回 strconv.ErrSyntax 错误。以下代码演示了此错误处理:

import (
    "fmt"
    "strconv"
)

func main() {
    s := "hello"
    
    if _, err := strconv.Atoi(s); err != strconv.ErrSyntax {
        fmt.Println("转换成功") // 不会执行,因为转换失败
    } else {
        fmt.Println("转换失败") // 输出 "转换失败"
    }
}

类型转换与空字符串

传递给 Atoi 函数的字符串不能是空的。否则,它会返回 strconv.ErrSyntax 错误。

import (
    "fmt"
    "strconv"
)

func main() {
    s := ""
    
    if _, err := strconv.Atoi(s); err != strconv.ErrSyntax {
        fmt.Println("转换成功") // 不会执行,因为转换失败
    } else {
        fmt.Println("转换失败") // 输出 "转换失败"
    }
}

The above is the detailed content of Learn Golang character conversion from scratch. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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