Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a single byte variable in go lang

Tags:

variables

go

byte

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.

like image 673
armnotstrong Avatar asked Jan 05 '15 08:01

armnotstrong


People also ask

How do you declare a byte value in Golang?

Go byte exampleWith the %c format verb, we print the character representation of the byte. We must explicitly set a variable to the byte type; otherwise, we get different types. In the code example, we have three variables. The a variable has byte data type.

How do you declare a byte variable?

byte Syntax in JAVA:byte Variable_Name = Value; For example: byte x = 10; Here x is variable name and 10 is a value assigned to a variable integer data type byte.

How do you create a byte array in Go?

To create a byte in Go, assign an ASCII character to a variable. A byte in Golang is an unsigned 8-bit integer. The byte type represents ASCII characters, while the rune data type represents a broader set of Unicode characters encoded in UTF-8 format.

What is [] uint8 in Golang?

type uint8 in Golang is the set of all unsigned 8-bit integers. The set ranges from 0 to 255. You should use type uint8 when you strictly want a positive integer in the range 0-255. Below is how you declare a variable of type uint8 : var var_name uint8.


2 Answers

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
like image 161
VonC Avatar answered Nov 05 '22 15:11

VonC


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'
like image 42
dyoo Avatar answered Nov 05 '22 13:11

dyoo