LoginSignup
14
7

More than 5 years have passed since last update.

【go】gorm.Modelを埋め込んだstructでIDを初期化する方法のメモ

Posted at

以下は unknown MyModel field 'ID' in struct literalというエラーになってしまう

go
package main

import (
    "fmt"
    "github.com/jinzhu/gorm"
)

type MyModel struct {
    gorm.Model
    Member string
}

func main() {
    m := MyModel{
        ID:     123,
        Member: "test",
    }

    fmt.Printf("%+v\n", m)
}

正しくはこうやる

go
package main

import (
    "fmt"
    "github.com/jinzhu/gorm"
)

type MyModel struct {
    gorm.Model
    Member string
}

func main() {
    m := MyModel{
        Model: gorm.Model{ID: 123},
        Member: "test",
    }

    fmt.Printf("%+v\n", m)
}

Modelで初期化するところがハマリどころでした。

14
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
7