首页 > 后端开发 > Golang > 正文

go语言怎么将整型转为字符串

青灯夜游
发布: 2022-12-28 10:35:09
原创
7898人浏览过
转换方法:1、用fmt包的Sprintf(),支持格式化变量转为字符串,语法“fmt.Sprintf("%d", num)”;2、用strconv包的Itoa(),支持将int类型转换成字符串,语法“strconv.Itoa(num)”;3、用strconv包的FormatInt(),支持将int64类型转换成字符串,语法“strconv.FormatInt(num,10)”。

go语言怎么将整型转为字符串

本教程操作环境:windows7系统、GO 1.18版本、Dell G3电脑。

在实际开发中我们往往需要对一些常用的数据类型进行转换,如 string、int、int64、float 等数据类型之间的转换。

int整数转字符串

1、fmt.Sprintf

fmt 包应该是最常见的了,从刚开始学习 Golang 就接触到了,写 ‘hello, world’ 就得用它。它还支持格式化变量转为字符串。%d 代表十进制整数。

立即学习go语言免费学习笔记(深入)”;

//Sprintf formats according to a format specifier and returns the resulting string.
func Sprintf(format string, a ...interface{}) string
登录后复制

使用示例:

str := fmt.Sprintf("%d", a)
登录后复制

2、strconv.Itoa

Go语言中的 strconv 包为我们提供了字符串和基本数据类型之间的转换功能。strconv 包中常用的函数包括 Atoi()、Itia()、parse 系列函数、format 系列函数、append 系列函数等。

其中Itoa()函数支持 int 类型转换成字符串

//Itoa is shorthand for FormatInt(int64(i), 10).
func Itoa(i int) string
登录后复制

使用示例:

func main() {
    num := 100
    str := strconv.Itoa(num)
    fmt.Printf("type:%T value:%#v\n", str, str)
}
登录后复制

运行结果如下所示:

1.png

3、strconv.FormatInt

支持 int64 类型转换成字符串
参数 i 是要被转换的整数, base 是进制,例如2进制,支持2到36进制。

//FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters ‘a' to ‘z' for digit values >= 10.
func FormatInt(i int64, base int) string
登录后复制

使用示例:

str := strconv.FormatInt(a, 10)
登录后复制

扩展知识:字符串转int整数

1、strconv.Atoi

比较常见的方法

// Atoi returns the result of ParseInt(s, 10, 0) converted to type int.
func Atoi(s string) (int, error)
登录后复制

使用示例:

i,err := strconv.Atoi(a)
登录后复制

2、strconv.ParseInt

功能非常强大

// ParseInt interprets a string s in the given base (0, 2 to 36) and
// bit size (0 to 64) and returns the corresponding value i.
func ParseInt(s string, base int, bitSize int) (i int64, err error)
登录后复制
  • 参数1 数字的字符串形式

  • 参数2 数字字符串的进制 比如二进制 八进制 十进制 十六进制

  • 参数3 返回结果的bit大小 也就是int8 int16 int32 int64

使用示例:

i, err := strconv.ParseInt("123", 10, 32)
登录后复制

【相关推荐:Go视频教程编程教学

以上就是go语言怎么将整型转为字符串的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号