首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【转】string类型和其他类型的值的互转

【转】string类型和其他类型的值的互转

作者头像
yiduwangkai
发布2019-09-17 16:10:13
1.4K0
发布2019-09-17 16:10:13
举报
文章被收录于专栏:大数据进阶大数据进阶

由于在开发过程中遇到类型转换问题,比如在web中某个参数是以string存在的,这个时候需要转换成其他类型,这里官方的strconv包里有这几种转换方法。

实现

有两个函数可以实现类型的互转(以int转string为例) 1. FormatInt (int64,base int)string 2. Itoa(int)string 打开strconv包可以发现Itoa的实现方式如下:

// Itoa is shorthand for FormatInt(int64(i), 10). func Itoa(i int) string { return FormatInt(int64(i), 10) }

也就是说itoa其实是更便捷版的FormatInt,以此类推,其他的实现也类似的。

示例

int 和string 互转 //int 转化为string s := strconv.Itoa(i) s := strconv.FormatInt(int64(i), 10) //强制转化为int64后使用FormatInt

//string 转为int i, err := strconv.Atoi(s)

int64 和 string 互转 //int64 转 string,第二个参数为基数 s := strconv.FormatInt(i64, 10) // string 转换为 int64 //第二参数为基数,后面为位数,可以转换为int32,int64等 i64, err := strconv.ParseInt(s, 10, 64)

float 和 string 互转 // flaot 转为string 最后一位是位数设置float32或float64 s1 := strconv.FormatFloat(v, 'E', -1, 32) //string 转 float 同样最后一位设置位数 v, err := strconv.ParseFloat(s, 32) v, err := strconv.atof32(s)

bool 和 string 互转 // ParseBool returns the boolean value represented by the string. // It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. // Any other value returns an error. func ParseBool(str string) (bool, error) { switch str { case "1", "t", "T", "true", "TRUE", "True": return true, nil case "0", "f", "F", "false", "FALSE", "False": return false, nil } return false, syntaxError("ParseBool", str) }

// FormatBool returns "true" or "false" according to the value of b func FormatBool(b bool) string { if b { return "true" } return "false" }

//上面是官方实现,不难发现字符串t,true,1都是真值。 //对应转换: b, err := strconv.ParseBool("true") // string 转bool s := strconv.FormatBool(true) // bool 转string

interface转其他类型 有时候返回值是interface类型的,直接赋值是无法转化的。 var a interface{} var b string a = "123" b = a.(string)

通过a.(string) 转化为string,通过v.(int)转化为类型。 可以通过a.(type)来判断a可以转为什么类型。

原文:https://blog.csdn.net/bobodem/article/details/80182096

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档