dongzhun6952 2018-03-12 13:21
浏览 112


How to bind data struct with database creation in Golang along with its tags/flags.

For example I have this code:

type User struct {
    ID      int     `sql:"primary_key;AUTO_INCREMENT"`
    Name    string  `sql:"type:varchar(100);unique"`
    Email   string  `sql:"type:varchar(100);unique"`
    Address string  `sql:"type:varchar(100)"`

When creating the database which should be based on this struct, I instead manually create it like this:

func (db *DB) CreateUserTable() (sql.Result, error) {

    statement := "CREATE TABLE IF NOT EXISTS %s (%s int, %s varchar, %s varchar, %s varchar)"
    return db.Exec(

How to bind the struct and its tags(primary key, NULL, etc) in database creation?. Is there best practice for it without using ORM libraries(gorm,etc)?

  • 写回答

1条回答 默认 最新

  • duanchong3075 2018-03-16 08:28

    You can use reflect to examine the struct and use it to construct your database query.

    For example:

    If you want to read struct's name to use it as table name:

    tableName := reflect.TypeOf(your-struct).Name()

    If you want to read struct's properties, loop and read it by using:

    val := reflect.ValueOf(your-struct)
    for i:=0; i < val.NumField(); i++ {
        field := val.Type().Field(i)
        tag := field.Tag
        fieldType := field.Type // get struct's variable type
        fieldName := field.Name //get struct variable's name
        fieldByTag1 := tag.Get("your-tag") // get struct tag's name 
        fieldByTag2 := tag.Get("your-another-tag") // get another struct tag's name(if you have more)

    Note that struct's tags are the one inside back tick -> `

    That's all you need to get from a struct. You should explore more in the documentation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 web课程,怎么做啊😭没好好听课 根本不知道怎么下手
  • ¥200 招个渗透测试兼职!需技术大拿!
  • ¥15 做一个关于单片机的比较难的代码,然后搞一个PPT进行解释
  • ¥40 matlab简单代码修改补充
  • ¥15 python提取.csv文件中的链接会经常出现爬取失败
  • ¥15 数据结构中的数组地址问题
  • ¥15 maya的mel里,怎样先选择模型A,然后利用mel脚本自动选择有相同名字的模型B呢。
  • ¥15 Python题,根本不会啊
  • ¥15 会会信号与系统和python的来
  • ¥15 关于#python#的问题