dongwei2882 2016-05-13 12:42
浏览 121
已采纳

在Go中将int转换为单个字节

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.

  • 写回答

2条回答 默认 最新

  • doudanglang5826 2016-05-13 12:50
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗