dongping1689 2015-01-05 08:13
浏览 243
已采纳

如何在Go lang中定义一个单字节变量

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.

  • 写回答

2条回答 默认 最新

  • douyi4912 2015-01-05 08:16
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题