如何在go lang中定义单个字节变量 [英] How to define a single byte variable in go lang

查看:183
本文介绍了如何在go lang中定义单个字节变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是golang的新手,希望找到一种方法来定义单一 字节变量。



这是 Effective Go 引用中的演示程序。

  package main 

导入(
fmt


func unhex(c字节)字节{
switch {
case'0 '< = c&& c< ='9':
返回c - '0'
案例'a'< = c&& c< ='f':
return c - 'a'+ 10
'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))
}

正如你看到的,我可以用数组包装一个字节,事情进行得很顺利,但是我怎样才能不使用数组定义一个字节?谢谢。

解决方案

在你的例子中,这可以工作,使用转换语法 T(x)

<$


lock $


$ b $ $ b

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


请参阅此运动场示例

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

输出:

  10 


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.

解决方案

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

这篇关于如何在go lang中定义单个字节变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆