go std strconv

strconv 是一个提供了字符串和其他基本类型相互转换的包

一般情况下,其他基本类型向 string 转换不会返回 error
而在 string 转向其他类型的时候,需要处理可能返回的 error

int <--> string 最简便的一种

var num0 int
var str0 string
init(num, str)

// int to string
str := strconv.ItoA(num0) // int 向 string 转换不返回 error

// string to int
num, err := strconv.Atoi(str0) // string 转向其他类型需要处理返回的 error
if err != nil {}

其他类型的转化具有一定的规律:

  1. string 转向其他类型 ParseXxxx() 需要处理 error
  2. 其他类型转向 string FormatXxxx() 不需要处理 error

Format -> string

s := strconv.FormatBool(true) // 将返回 "true"
s := strconv.FormatFloat(3.1415, 'E', -1, 64) // 
s := strconv.FormatInt(-42, 16) // 指定转换后的进制,这里指定为16,即转换成16进制形式的 string
s := strconv.FormatUint(42, 16)

Parse -> 其他类型

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

Quote/QuoteXxx 在字符串或者字符前后加引号

s := "Hello, world! 你好,世界!"
word := '我'
s0 := strconv.Quote(s) // 在字符串前后加引号
s1 := strconv.QuoteToASCII(s) // 加引号,非 ascii 则进行编码
s3 := strconv.QuoteRune(word) // 在 Rune 前后加引号

结果:

"Hello, world! 你好,世界!"
"Hello, world! \u4f60\u597d\uff0c\u4e16\u754c\uff01"
'我'

posted on   Slime04  阅读(23)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示