Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to organize a Go interface

Tags:

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

like image 609
Metropolis Avatar asked May 21 '10 22:05

Metropolis


1 Answers

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.

like image 50
Arkku Avatar answered Sep 21 '22 12:09

Arkku