你应该如何组织你的Go文件以支持跨平台构建并确保一致性?

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

How should I organize my go files to support cross platform builds and enforce consistency?

问题

我目前使用的方法是,我有一个“基础”文件,用于定义包的类型、接口和基本API。然后我创建一个_windows.go_linux.go文件,并添加特定于平台的类型,然后将接口应用到这些类型上。设置基本上是这样的:http://play.golang.org/p/2DJxTuSAIh。

  1. 这被认为是最佳实践吗?
  2. 在团队环境中,这是否有助于一些开发人员专注于Linux,而另一些开发人员专注于Windows?也就是说,如果接口发生变化,两个团队都会通过构建失败得到通知吗?
英文:

I'm currently using a method where I have a "base" file that defines the types, interfaces and a basic API for the package. I then create an _windows.go and _linux.go file and add platform specific types that I can apply the interface to. The setup is basically like this: http://play.golang.org/p/2DJxTuSAIh.

  1. Is this considered best practice?
  2. Would this assist in a team setting where some developers are linux focused and some windows focused, i.e. if the interface changes both teams will be notified via build failure?

答案1

得分: 2

接口的使用是一个正交的概念。在适当的GOOS和GOARCH文件中,使用与接口同名的实现通常更简单。

在标准库中也使用了与你的示例类似的使用共同构造函数名的方法,以及将全局变量名赋值给函数的方法(在概念上与前一种方法类似)。

由于Go是静态类型的,并且不能重新声明全局标识符,构建系统将始终捕获问题;只需要测试所有适用的系统,以确保没有任何过时的操作系统或架构实现。

英文:

The use of interfaces is an orthogonal concept. Use an interface where an interface makes sense, but it's often simpler just provide an implementation by the same name in the proper GOOS and GOARCH files.

The method of using a common constructor name (from your example) is also used in places in the std lib, as is the method of assigning a global variable name to a function (which is similar in concept to the former method).

Because Go is statically typed, and you can't redeclare global identifiers, the build system will always catch problems; it's just a matter of testing for all applicable systems to ensure that no OS or ARCH has an out of date implementation.

huangapple
  • 本文由 发表于 2015年9月3日 01:54:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/32360022.html
匿名

发表评论

匿名网友

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

确定