In which order should I write a Go package?

When I ask about the order I mean this:

// Comment explaining how the package works

package name

import (
  [...]
)

const  (
  [...]
)

var  (
  [...]
)

type SomeNameOfStruct struct {
  [...]
}

//exportables functions
func Action() {
   [...]
}

//functions of each struct
func (s *SomeNameOfStruct) Get(name string)  error {
   [...]
}

//non-exportable functions
func miniActions() {
 [...]
}

//what else is missing?

Well, that, what is the order that follows a consistent style with most of the packages that I may encounter?

I think the most common convention is to have package as first, for obvious reasons, followed by imports.

After that usually stuff gets grouped by function, rather than being forced into an arbitrarily choosen order based on nothing.

1 Like

The stdlib is the only source of truth:

1.Package name and imports
2.Types
3.Global Constants and Var (and than eventually the init() function)
4.Type Methods

Utils functions (or private methods) should follow the other utils function or the type method that calls them.
Constants only used in a specific function or method should be defined before the function/method.
One good part of golang is the freedom of declarations, like interfaces which are declared when you need them.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.