我是golang的新手,想找到一种定义单个 byte变量的方法.
这是Effective Go参考中的演示程序.
package main
import (
"fmt"
)
func unhex(c byte) byte{
switch {
case '0' <= c && c <= '9':
return c - '0'
case 'a' <= c && c <= 'f':
return c - 'a' + 10
case 'A' <= c && c <= 'F':
return c - 'A' + 10
}
return 0
}
func main(){
// It works fine here, as I wrap things with array.
c := []byte{'A'}
fmt.Println(unhex(c[0]))
//c := byte{'A'} **Error** invalid type for composite literal: byte
//fmt.Println(unhex(c))
}
Run Code Online (Sandbox Code Playgroud)
如你所见,我可以用数组包装一个字节,事情很顺利,但如何在不使用数组的情况下定义单个字节?谢谢.
在您的示例中,这将使用转换语法T(x):
c := byte('A')
Run Code Online (Sandbox Code Playgroud)
转换是表单的表达式,
T(x)其中T是一个类型,x是一个可以转换为类型的表达式T.
看这个游乐场的例子.
cb := byte('A')
fmt.Println(unhex(cb))
Run Code Online (Sandbox Code Playgroud)
输出:
10
Run Code Online (Sandbox Code Playgroud)