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 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波