How to define a single byte variable in go lang

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

How to define a single byte variable in go lang

问题

我是一个对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(){
    // 在这里使用数组包装起来是可以的
    c := []byte{'A'}
    fmt.Println(unhex(c[0]))
    
    //c := byte{'A'}    **错误** 无效的复合字面量类型:byte
    //fmt.Println(unhex(c))
}

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

英文:

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.

package main

import (
   &quot;fmt&quot;
)

func unhex(c byte) byte{
    switch {
    case &#39;0&#39; &lt;= c &amp;&amp; c &lt;= &#39;9&#39;:
        return c - &#39;0&#39;
    case &#39;a&#39; &lt;= c &amp;&amp; c &lt;= &#39;f&#39;:
        return c - &#39;a&#39; + 10
    case &#39;A&#39; &lt;= c &amp;&amp; c &lt;= &#39;F&#39;:
        return c - &#39;A&#39; + 10
    }
    return 0
}

func main(){
    // It works fine here, as I wrap things with array.
    c := []byte{&#39;A&#39;}
    fmt.Println(unhex(c[0]))
    
    //c := byte{&#39;A&#39;}    **Error** invalid type for composite literal: byte
    //fmt.Println(unhex(c))
}

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)来实现:

c := byte('A')

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

请参考这个示例

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

输出结果:

10
英文:

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

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.

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

Output:

10

答案2

得分: 3

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

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:

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:

确定