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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With