How to define a single byte variable in go lang

﹥>﹥吖頭↗ 提交于 2019-12-22 09:19:46

问题


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 (
   "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))
}

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:


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

c := byte('A')

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('A')
fmt.Println(unhex(cb))

Output:

10



回答2:


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 = 'A'


来源:https://stackoverflow.com/questions/27775590/how-to-define-a-single-byte-variable-in-go-lang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!