2

I want to create a struct to represent a DB model using Go with gorm. I have a table with records that have a field of type bit(1) which represents a binary value (0 or 1).

How can i make sure it doesn't "conflict" with my Go struct definition? I guess using bool as a type is not the correct answer?

Gambit2007
  • 3,260
  • 13
  • 46
  • 86
  • 2
    There's no `bit` type in Go, you'll have to choose from the primitives that are [builtin](https://golang.org/pkg/builtin/). – mkopriva Nov 07 '19 at 18:41
  • But then won't i get an error, for example, when i would try to put the value `1` into a field that's defined as `bool`? – Gambit2007 Nov 07 '19 at 18:48
  • 1
    ... using `bool` directly I would say is incorrect, or at the least confusing, however you can declare a new type from `bool`, have that new type implement the Valuer and Scanner interfaces to properly translate the values between the app and db layers . Additionally you may also want to declare constants to represent `0` and `1` and use those constants instead of the `0` and `1`. – mkopriva Nov 07 '19 at 18:54
  • from https://godoc.org/database/sql#Rows.Scan `For scanning into *bool, the source may be true, false, 1, 0, or string inputs parseable by strconv.ParseBool.` Check out the strconv.ParseBool function. Putting `1` into a bool field will translate just fine. We do this without any problems (so far). I know that the `gorm` package auto migrate command represents bools as bit(1) by default for at least one databse system so it seems like a popular convention – Sebastian Nov 08 '19 at 20:47

0 Answers0