douzuqin3467 2010-05-21 22:38
浏览 9
已采纳

组织Go界面的最佳方法

Its been a long time since I have programmed in C++, but I know that in C++ the classes are organized into .h files and .cpp files. Also many other languages benefit from splitting up code into logical groupings within a directory structure to improve organization.

Well I am trying to learn Go now and I was reading over the Go for C++ Programmers article when I came upon interfaces. The article explains that interfaces in Go essentially take the place of classes, and shows how to set them up pretty well.

What I am trying to figure out though is how should I organize an interface into files? For instance, should the interface be in one file while the implementation is in another?

myInterface.go

type myInterface interface {
    get() int
    set(i int)
}


myImplementation.go

type myType struct { i int }
func (p *myType) set(i int) { p.i = i }
func (p *myType) get() int { return p.i }

My code here may be wrong since I do not completely know what I am doing yet (and if I am wrong please correct me), but would this be the best way to set this up? Im having a very hard time trying to wrap my head around how to organize code in Go so any help is appreciated!

Metropolis

  • 写回答

2条回答 默认 最新

  • douxiong2001 2010-05-22 01:48
    关注

    There is no need to put types and interfaces in separate files. The things exported from each package are what matters and you denote those by beginning the name with a capital letter. In C & co. what goes into a header file matters because that's the thing “imported” (included). In Go it's the package that is imported, and it doesn't matter how its contents are organised into different source files (it won't be visible to the importer anyhow).

    My personal recommendation is to avoid creating unnecessary files. If the code is relatively short, keep it in one file. If it's long, then consider splitting off parts for which it feels natural to do so (e.g. interface + related functions that would be probably form a separate class if you were doing it in Java or C++). Don't split off anything just for the sake of separating definitions from code; it doesn't make sense in Go even though it does in C.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 ue5运行的通道视频都会有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数