doushenken2833 2018-11-21 17:16 采纳率: 0%
浏览 676
已采纳

将bool转换为tinyint golang

I am using the latest version of xorm and want to create a simple go struct as follows:

types myStruct struct {
    isDeleted bool `xorm:"'isDeleted' tinyint(3)"`
}

I know the bool type in go evaluates to true and false, but I need to map it to a mySql database where the values are tinyint(3) and 1 maps to true and 0 to false. In the example above no matter what my post requests look like isDeleted always evaluates to 0. Thanks in advance for any advice on this issue. This https://github.com/go-xorm/xorm/issues/673 may provide some context.

  • 写回答

1条回答 默认 最新

  • douxin20081125 2018-11-21 18:09
    关注

    I'm not sure what/if xorm can do about it, but you can just create a type and implement the Valuer and Scanner interfaces for it. Here is an example I did a pull request for using a bit(1) for a bool.

    https://github.com/jmoiron/sqlx/blob/master/types/types.go#L152

    For an integer, you would just return the int instead of a []byte containing the int. Like so:

    type IntBool bool
    
    // Value implements the driver.Valuer interface,
    // and turns the IntBool into an integer for MySQL storage.
    func (i IntBool) Value() (driver.Value, error) {
        if i {
            return 1, nil
        }
        return 0, nil
    }
    
    // Scan implements the sql.Scanner interface,
    // and turns the int incoming from MySQL into an IntBool
    func (i *IntBool) Scan(src interface{}) error {
        v, ok := src.(int)
        if !ok {
            return errors.New("bad int type assertion")
        }
        *i = v == 1
        return nil
    }
    

    Then your struct would just use the new type

    type myStruct struct {
        isDeleted IntBool `xorm:"'isDeleted' tinyint(3)"`
    }
    

    But, again, is there any particular reason you declared this boolean value as a tinyint? MySQL has a boolean type and things would just work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况