切片无法转换为字符串

时间:2015-01-26 14:40:00

标签: string go type-conversion slice

func (this *AdminModel) Login(v_name string, v_pwd string) (bool, error, uint) {
    o := orm.NewOrm()
    v_pwd_encrypt_byte := md5.Sum([]byte(v_pwd))
    v_pwd_encrypt := string(v_pwd_encrypt_byte[:])
    t_admin := Admin{Name: v_name, Pwd: v_pwd_encrypt}
    fmt.Printf("username:%v  password:%v\n", v_name, v_pwd_encrypt_byte)
    fmt.Printf("username:%v  password:%v\n", v_name, v_pwd_encrypt_byte[:])
    fmt.Printf("username:%v  password:%v\n", v_name, v_pwd_encrypt)
    err := o.Read(&t_admin, "Name", "Pwd")
    if err != nil {
        return false, err, 0
    } else {
        return true, nil, t_admin.Id
    }
}

打印结果:

username:yuhaya  password:[97 22 175 237 203 11 195 16 131 147 92 28 38 47 244 201]
username:yuhaya  password:[97 22 175 237 203 11 195 16 131 147 92 28 38 47 244 201]
username:yuhaya  password:a???
                          ???\&/??

为什么打印的最后一行会出现乱码?

v_pwd_encrypt := string(v_pwd_encrypt_byte[:])

此职位是否无法转换?

2 个答案:

答案 0 :(得分:2)

添加到@ Ainar-G的答案,hex.EncodeToString是最有效的方式,因为它不涉及fmt.Sprintf之类的反射或类型猜测。

func main() {
    sum := md5.Sum([]byte("meh"))
    stringSum := hex.EncodeToString(sum[:])
    fmt.Println(stringSum)
}

答案 1 :(得分:1)

md5.Sum()返回字节,不是可打印的ASCII字符。如果要查看这些字节的十六进制表示,可以使用fmt.Sprintf("%x", ...),如下所示:

v_pwd_encrypt := fmt.Sprintf("%x", v_pwd_encrypt_byte)