dongqufi82315 2017-02-17 07:19
浏览 28
已采纳

转到:暴露的别名结构无法分配给内部结构文字

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条回答 默认 最新

  • douliu7929 2017-02-17 07:45
    关注

    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",
            },
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件