哪家公司做网站专业,手机安装wordpress,简洁高端的wordpress个人博客,淘宝商家版登录入口问题 由于在开发过程中遇到类型转换问题#xff0c;比如在web中某个参数是以string存在的#xff0c;这个时候需要转换成其他类型#xff0c;这里官方的strconv包里有这几种转换方法。 实现 有两个函数可以实现类型的互转#xff08;以int转string为例#xff09; 1. For… 问题 由于在开发过程中遇到类型转换问题比如在web中某个参数是以string存在的这个时候需要转换成其他类型这里官方的strconv包里有这几种转换方法。 实现 有两个函数可以实现类型的互转以int转string为例 1. FormatInt int64base intstring 2. Itoaintstring 打开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
//第二参数为基数后面为位数可以转换为int32int64等
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, nilcase 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
}//上面是官方实现不难发现字符串ttrue1都是真值。
//对应转换
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可以转为什么类型。