【golang踩“坑”记】 string(fid) 与 strconv.Itoa(fid)

踩坑记 string(fid) 与 strconv.Itoa(fid)

遇到坑

在用golang做laravel进程管理的时候,发现一个“坑”:

strconv.Itoa(fid) 才能达到想要的数字字符
string(fid) 并不能!!(因为该转换会将数字直接转换为该数字对应的内码)

    fidstr := strconv.Itoa(fid)
    fidstr := string(fid) 
    fmt.Printf("exec: %s %s %s %s\n",php, artisan, option, fidstr)
    cmd := exec.Command(br.php, br.artisan, br.option, fidstr)

当且仅当 data[]byte类型时 string(data) 才能达到想要的目标。
而其他情况,则需要根据类型来转换:

比如: strconv.Itoa(int),否则得到的不是我们想要。

测试两种方式的 ASCII 值

看测试代码

func Test_IntToString(t *testing.T) {
    fmt.Printf("string(1) = %v\n", []byte(string(1)))
    fmt.Printf("strconv.Itoa(1) = %v\n", []byte(strconv.Itoa(1)))
}

我们得到运行如下结果:

string(1) = [1]
strconv.Itoa(1) = [49]

结论已经很明显,string(int) 会将整数直译为ASCII编码,
strconv.Itoa(int) 才会转换成对应的数字字符在ASACII编码。

    原文作者:NIL
    原文地址: https://segmentfault.com/a/1190000013209393
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞