4

https://github.com/tarm/serial/blob/master/serial.go#L103

type StopBits byte
type Parity byte

type Config struct {
    Name        string
    Baud        int
    ReadTimeout time.Duration
    Size byte
    Parity Parity
    StopBits StopBits
}

I am trying to flag the command line and fill in the config struct but i can't figure out how to go from int or string to a single byte?

example size 7

Tried

mysize := "7"
mysize[0]

but then tarm/serial tells me invalid input error in the serial.Config

i, err := strconv.Atoi("7")

compiler complains that i can't do i.(byte)

The only way I can make it work is to hardcode size: 7 in the config struct.

Gert Cuykens
  • 6,515
  • 11
  • 47
  • 82
  • `byte(i)` or `[]byte(string(i))` to set an int to a byte. See https://stackoverflow.com/a/62737936/12817546. `strconv.Atoi(s)` and `byte(i)` to set a string to a byte. See https://stackoverflow.com/a/62740786/12817546. `int(b)` or `int(b[0])` to set a byte to an int. See https://stackoverflow.com/a/62725637/12817546. –  Jul 09 '20 at 01:33

3 Answers3

17

You can just convert an int to a byte: https://play.golang.org/p/w0uBGiYOKP

val := "7"
i, _ := strconv.Atoi(val)
byteI := byte(i)
fmt.Printf("%v (%T)", byteI, byteI)

compiler complains that i can't do i.(byte)

Of course, because that is a type assertion, it will fail if i is not of the given type (byte in your example) or it's not an interface.

Duru Can Celasun
  • 1,501
  • 1
  • 17
  • 28
4

In order to use a type assertion (which you're doing), you need to have an interface on the left. You're likely receiving an error along the lines of "non-interface type byte on left"-- which is true, because you already know the type. Instead, you should be casting.

You'll want to use byte(i) instead of i.(byte):

i := 12
c := byte(i)
fmt.Println(c) //12

Be careful when you have an int that exceeds the max int a byte can hold; you will end up overflowing the byte. In this case, if it's over 255 (the most a single byte can hold), you'll overflow.

william.taylor.09
  • 2,054
  • 9
  • 17
-1
    str := "Hello"
    var b byte
    for i,_ := range str{
        b = str[i]
        fmt.Println(b)
    }
Inasa Xia
  • 322
  • 4
  • 8