How to define a single byte variable in go lang

huangapple go评论113阅读模式
英文:

How to define a single byte variable in go lang

问题

我是一个对golang新手,想找到一种定义单个 byte 变量的方法。

这是《Effective Go》参考手册中的一个演示程序。

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func unhex(c byte) byte{
  6. switch {
  7. case '0' <= c && c <= '9':
  8. return c - '0'
  9. case 'a' <= c && c <= 'f':
  10. return c - 'a' + 10
  11. case 'A' <= c && c <= 'F':
  12. return c - 'A' + 10
  13. }
  14. return 0
  15. }
  16. func main(){
  17. // 在这里使用数组包装起来是可以的
  18. c := []byte{'A'}
  19. fmt.Println(unhex(c[0]))
  20. //c := byte{'A'} **错误** 无效的复合字面量类型:byte
  21. //fmt.Println(unhex(c))
  22. }

你可以看到,我可以用数组包装一个字节,一切都正常,但是如果不使用数组,我该如何定义一个单个字节呢?谢谢。

英文:

I am a newbie to golang and want to find a way to define a single byte variable.

It's a demo program in Effective Go reference.

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. )
  5. func unhex(c byte) byte{
  6. switch {
  7. case &#39;0&#39; &lt;= c &amp;&amp; c &lt;= &#39;9&#39;:
  8. return c - &#39;0&#39;
  9. case &#39;a&#39; &lt;= c &amp;&amp; c &lt;= &#39;f&#39;:
  10. return c - &#39;a&#39; + 10
  11. case &#39;A&#39; &lt;= c &amp;&amp; c &lt;= &#39;F&#39;:
  12. return c - &#39;A&#39; + 10
  13. }
  14. return 0
  15. }
  16. func main(){
  17. // It works fine here, as I wrap things with array.
  18. c := []byte{&#39;A&#39;}
  19. fmt.Println(unhex(c[0]))
  20. //c := byte{&#39;A&#39;} **Error** invalid type for composite literal: byte
  21. //fmt.Println(unhex(c))
  22. }

As you see I can wrap a byte with array, things goes fine, but How can I define a single byte without using array? thanks.

答案1

得分: 14

在你的示例中,可以使用转换语法 T(x)来实现:

  1. c := byte('A')

转换是形式为 T(x) 的表达式,其中 T 是类型,x 是可以转换为类型 T 的表达式。

请参考这个示例

  1. cb := byte('A')
  2. fmt.Println(unhex(cb))

输出结果:

  1. 10
英文:

In your example, this would work, using the conversion syntax T(x):

  1. c := byte(&#39;A&#39;)

> Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T.

See this playground example.

  1. cb := byte(&#39;A&#39;)
  2. fmt.Println(unhex(cb))

Output:

  1. 10

答案2

得分: 3

如果你不想使用:=语法,你仍然可以使用var语句,它允许你显式地指定类型。例如:

  1. var c byte = 'A'
英文:

If you don't want to use the := syntax, you can still use a var statement, which lets you explicitly specify the type. e.g:

  1. var c byte = &#39;A&#39;

huangapple
  • 本文由 发表于 2015年1月5日 16:13:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/27775590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定