I arrange my models in this way:
-
projectDir
main.go
-
models
- models.go
- modelA
- modelA.go
- modelB
- modelB.go
In main.go
:
package main
import (
"test.local/projectDir/models"
)
func main() {
modelA := models.ModelA{
FieldA: "xx",
FieldB: models.ModelB{
FiledC: "yy"
} // here will raise a error: cannot use models.ModelB literal (type models.ModelB) as type modelB.ModelB in field value
}
}
In models/models.go
:
package models
import (
"test.local/projectDir/models/modelA"
"test.local/projectDir/models/modelB"
)
type ModelA modelA.ModelA
type ModelB modelB.ModelB
In models/modelA/modelA.go
:
package modelA
import (
"test.local/projectDir/models/modelB"
)
type ModelA struct {
fieldA string
fieldB modelB.ModelB
}
In models/modelB/modelB.go
:
package modelB
type ModelB struct {
fieldC string
}
As the error point out, the struct type is different. Is there a better way to organize the models?