首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将bool转换为tinyint golang

将bool转换为tinyint golang
EN

Stack Overflow用户
提问于 2018-11-21 17:16:02
回答 1查看 4.9K关注 0票数 1

我使用的是最新版本的xorm,并希望创建一个简单的go结构,如下所示:

代码语言:javascript
复制
types myStruct struct {
    isDeleted bool `xorm:"'isDeleted' tinyint(3)"`
}

我知道go中的bool类型为true和false,但我需要将其映射到mySql数据库,其中值为tinyint(3),1映射为true,0映射为false。在上面的例子中,无论我的post请求看起来像什么,isDeleted总是计算为0。提前感谢您对此问题的任何建议。这个https://github.com/go-xorm/xorm/issues/673可能提供一些上下文。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-21 18:09:02

我不知道xorm能做些什么,但是您可以为它创建一个类型并实现ValuerScanner接口。下面是一个示例,我为bit(1)bool使用了一个拉请求。

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

对于整数,只需返回int,而不是包含int[]byte。就像这样:

代码语言:javascript
复制
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
}

然后,您的结构将只使用新类型。

代码语言:javascript
复制
type myStruct struct {
    isDeleted IntBool `xorm:"'isDeleted' tinyint(3)"`
}

但是,再次声明这个布尔值为tinyint有什么特别的原因吗?MySQL 有一个布尔类型的,一切都会正常工作的。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53417403

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档