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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址