gpt4 book ai didi

variables - 如何在go lang中定义一个单字节变量

转载 作者:IT王子 更新时间:2023-10-29 00:51:22 25 4
gpt4 key购买 nike

我是 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(){
// 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))
}

如您所见,我可以用数组包装一个字节,一切正常,但是如何在不使用数组的情况下定义单个字节?谢谢。

最佳答案

在您的示例中,这会起作用,使用 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.

参见 this playground example .

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

输出:

10

关于variables - 如何在go lang中定义一个单字节变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27775590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com