登录
首页 >  Golang >  Go问答

将 bool 转换为tinyint golang

来源:stackoverflow

时间:2024-04-12 09:36:33 245浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《将 bool 转换为tinyint golang》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

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

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

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


解决方案


我不确定 xorm 可以做什么,但您可以创建一个类型并为其实现 valuerscanner 接口。这是我为 bool 使用 bit(1) 发出的拉取请求的示例。

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

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

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
}

那么你的结构将只使用新类型

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

但是,您是否有任何特殊原因将此布尔值声明为 tinyint ? mysql 布尔类型,一切都会正常工作。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>