暴露的别名结构体无法分配给内部结构体字面量。

huangapple go评论86阅读模式
英文:

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",
        },
    }
}

huangapple
  • 本文由 发表于 2017年2月17日 15:19:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/42291709.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定