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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?