Google BigQuery DATE类型字段在Go结构体中的映射方法
解决Go中映射BigQuery DATE类型字段的问题
在Go里处理BigQuery的DATE类型字段,最贴合的方式是用cloud.google.com/go/bigquery包提供的Date类型——这是官方专门为BigQuery DATE类型设计的类型,能直接和字段映射,不需要额外做字符串格式化。
正确的结构体定义
import "cloud.google.com/go/bigquery" type Record struct { Date bigquery.Date `bigquery:"the_date"` }
这样调用iterator.Next(&record)就不会再出现类型不匹配的错误了。
转换成标准time.Time(可选)
如果需要把bigquery.Date转成标准库的time.Time,可以用它的Time()方法,默认返回UTC时区、时分秒为0的时间:
t := record.Date.Time() // 得到time.Time类型的时间
自定义类型映射(进阶可选)
要是你更倾向于直接用time.Time作为结构体字段,可以自定义一个类型,实现sql.Scanner和driver.Valuer接口来手动处理转换逻辑:
import ( "database/sql/driver" "fmt" "time" "cloud.google.com/go/bigquery" ) type BQDate time.Time func (d *BQDate) Scan(value interface{}) error { bqDate, ok := value.(bigquery.Date) if !ok { return fmt.Errorf("期望bigquery.Date类型,实际得到%T", value) } *d = BQDate(bqDate.Time()) return nil } func (d BQDate) Value() (driver.Value, error) { t := time.Time(d) return bigquery.DateFrom(t), nil } // 之后结构体可以这么定义 type Record struct { Date BQDate `bigquery:"the_date"` }
不过这种方式不如直接用官方的bigquery.Date简洁,优先推荐用官方提供的类型。
内容的提问来源于stack exchange,提问作者user22335954
相关产品推荐
相关产品推荐

