Home  >  Article  >  Backend Development  >  How should I map MySQL\'s `bit(1)` type to a Go type?

How should I map MySQL\'s `bit(1)` type to a Go type?

Susan Sarandon
Susan SarandonOriginal
2024-11-23 06:41:16822browse

How should I map MySQL's `bit(1)` type to a Go type?

How to Map MySQL's bit Type to Go's Type

In MySQL, the bit(1) data type is used to store Boolean values. When migrating to Go, developers often face the challenge of determining the appropriate Go type to map it to.

Question:
In the provided example, the MySQL table contains a column named deleted of type bit(1). What Go type should be used to represent this column in a Go struct?

Answer:
The recommended approach is to use a custom data type, as provided by the sqlx library. sqlx defines a type called BitBool that specifically handles BIT(1) values:

// BitBool is an implementation of a bool for the MySQL type BIT(1).
// This type allows you to avoid wasting an entire byte for MySQL's boolean type TINYINT.
type BitBool bool

BitBool implements the necessary interfaces to convert between Go's bool type and MySQL's BIT(1) type:

// Value implements the driver.Valuer interface,
// and turns the BitBool into a bitfield (BIT(1)) for MySQL storage.
func (b BitBool) Value() (driver.Value, error) {
    if b {
        return []byte{1}, nil
    } else {
        return []byte{0}, nil
    }
}

// Scan implements the sql.Scanner interface,
// and turns the bitfield incoming from MySQL into a BitBool
func (b *BitBool) Scan(src interface{}) error {
    v, ok := src.([]byte)
    if !ok {
        return errors.New("bad []byte type assertion")
    }
    *b = v[0] == 1
    return nil
}

In the provided Go struct, Deleted should be declared as:

Deleted     BitBool `form:"-"`

The above is the detailed content of How should I map MySQL\'s `bit(1)` type to a Go type?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn