英文:
go: exposed alias struct can't assign to inner struct literal
问题
我将我的模型安排如下:
- projectDir
-
main.go
-
models
- models.go
- modelA
- modelA.go
- modelB
- modelB.go
-
在 main.go
中:
package main
import (
"test.local/projectDir/models"
)
func main() {
modelA := models.ModelA{
FieldA: "xx",
FieldB: models.ModelB{
FiledC: "yy",
}, // 这里会报错:无法将 models.ModelB 字面量(类型为 models.ModelB)用作 modelB.ModelB 字段值的类型
}
}
在 models/models.go
中:
package models
import (
"test.local/projectDir/models/modelA"
"test.local/projectDir/models/modelB"
)
type ModelA modelA.ModelA
type ModelB modelB.ModelB
在 models/modelA/modelA.go
中:
package modelA
import (
"test.local/projectDir/models/modelB"
)
type ModelA struct {
FieldA string
FieldB modelB.ModelB
}
在 models/modelB/modelB.go
中:
package modelB
type ModelB struct {
FieldC string
}
正如错误所指出的那样,结构体类型不同。有没有更好的方法来组织这些模型?
英文:
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?
答案1
得分: 1
错误是很明显的:你试图将错误的值(models.ModelB
)赋给ModelB.modelB
结构体。
你可以通过导入正确的包来轻松解决这个问题:
import (
"test.local/projectDir/models/modelB"
)
func main() {
modelA := models.ModelA{
FieldA: "xx",
FieldB: modelB{
FiledC: "yy",
},
}
}
英文:
The error is self explanatory: you are trying to assign the wrong value (models.ModelB
) to a ModelB.modelB
struct.
You can easily solve this issue by importing the correct package:
import (
"test.local/projectDir/models/modelB"
)
func main() {
modelA := models.ModelA{
FieldA: "xx",
FieldB: modelB{
FiledC: "yy",
},
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论