doushi4795 2018-11-17 20:46
浏览 269
已采纳

错误:此包装中已重新声明类型

I have this folder structure:

In req.go, I have:

package basic

type Headers struct {
}

type Body struct {
}

and in res.go, I have the same:

package basic

type Headers struct {
}

type Body struct {
}

and so I get this error:

'Headers' redeclared in this package

'Body' redeclared in this package

Is the only way to solve this is to put req and res in their own folders? Ughh so many folders.

  • 写回答

1条回答 默认 最新

  • duanchen7703 2018-11-17 21:15
    关注

    Packages are the basic unit of creating separated and reusable code. From inside the package, you refer to its identifiers (identifiers declared in the package) by their name. From the "outside" (from other packages), you import the package and you refer to its identifiers using a qualified identifier, which is

    QualifiedIdent = PackageName "." identifier .
    

    When a package consists of multiple files, each identifier declared in any of the package's files will belong to the package block. Quoting from Spec: Declarations and scope:

    The scope of an identifier denoting a constant, type, variable, or function (but not method) declared at top level (outside any function) is the package block.

    What this means is that you can't have the same identifier declared in 2 files of the same package.

    If you think about it, this is how it should be. What happens if someone from the outside writes basic.Header? Which Header should that mean?

    One option is to put them into 2 separate packages: req and resp, then you can refer to them as req.Header and resp.Header, and you know exactly what they mean just by looking at these qualified identifiers.

    If you don't want 2 packages, simply rename them. Give them meaningful names, such as ReqHeader and RespHeader, and then you may refer to them like basic.ReqHeader and basic.RespHeader.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 github训练的模型参数无法下载
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题