11 go
http://play.golang.org/p/BoZkHC8_uA
我想将uint8转换为字符串,但无法弄清楚如何.
package main
import "fmt"
import "strconv"
func main() {
str := "Hello"
fmt.Println(str[1]) // 101
fmt.Println(strconv.Itoa(str[1]))
}
Run Code Online (Sandbox Code Playgroud)
这给了我 prog.go:11: cannot use str[1] (type uint8) as type int in function argument
[process exited with non-zero status]
任何的想法?
小智 8
转换或投射之间存在差异,请考虑:
var s uint8 = 10
fmt.Print(string(s))
fmt.Print(strconv.Itoa(int(s)))
Run Code Online (Sandbox Code Playgroud)
字符串强制转换打印'\n'(换行符),字符串转换打印"10".一旦您考虑两种变体的[]字节转换,差异就会变得清晰:
[]byte(string(s)) == [10] // the single character represented by 10
[]byte(strconv.Itoa(int(s))) == [49, 48] // character encoding for '1' and '0'
Run Code Online (Sandbox Code Playgroud)
请参阅play.golang.org中的此代码
你可以通过使用cast来更简单地做到这一点,这对我有用:
var c uint8
c = 't'
fmt.Printf(string(c))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29541 次 |
| 最近记录: |