dongqi8863 2014-06-17 12:58
浏览 282
已采纳

将枚举值保存到数据库

I'm new to Go and I'm trying to write a little program to save enumerated values to a database. The way I declare my values is as follows:

type FileType int64
const (
    movie FileType = iota
    music
    book
    etc
)

I use these values in my struct like this:

type File struct {
    Name     string
    Type     FileType
    Size     int64
}

I use gorp for my database stuff, but I guess the use of gorp isn't relevant to my problem. I put stuff in my DB like this:

dbmap.Insert(&File{"MyBook.pdf",movie,1000})

but when I try to retrieve stuff…

dbmap.Select(&dbFiles, "select * from Files")

I get the following error:

panic: reflect.Set: value of type int64 is not assignable to type main.FileType

When I use int64 as the type for the const(...) and for the File.Type field, everything works fine, but I'm new to Go and want to understand the problem. The way I see it, I have two problems:

  1. Why can't Go convert this stuff successfully? I looked at the source code of the Go reflection and sql packages and there are methods for this kind of conversion, but they seem to fail. Is this a bug? What is the problem?
  2. I figured out, that one can implement the sql.Scanner interface by implementing the following method:

    Scan(src interface{}) error
    

    I tried to implement the method and I even was able to get the right value from src and convert it to a FileType, but I was confused if I should implement the method for "(f *FileType) or (f FileType). Either way the method gets invoked, however I'm not able to overwrite f (or at least the update gets lost later) and the File instances read from the DB always had a "0" as value for File.Type.

Do you have any ideas on those two points?

  • 写回答

3条回答 默认 最新

  • douyi3307 2014-08-19 02:48
    关注

    I recently had the same need, and the solution is to implement two interfaces:

    1. sql/driver.Valuer
    2. sql.Scanner

    Here's a working example:

    type FileType int64
    
    func (u *FileType) Scan(value interface{}) error { *u = FileType(value.(int64)); return nil }
    func (u FileType) Value() (driver.Value, error)  { return int64(u), nil }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能