How do you organize go methods / code?

Supposing the following example:

package main

import "fmt"

type IReport interface {
	DisplayName()
}

type Person struct {
	Name string
}

func (p *Person) DisplayName() {
	if p == nil {
		fmt.Println("<no name provided>\n")
		return
	}
	fmt.Println(p.Name)
}

func main() {
	var p *Person = nil
	var i IReport = p
	describe(i)
	i.DisplayName()

	i = &Person{"Julia"}
	describe(i)
	i.DisplayName()
}

func describe(i IReport) {
	fmt.Printf("(%+v, %T)\n", i, i)
}

What are the best practice for organizing these methods?
Should we code in this order?

    1. declare interfaces
    1. declare types
    1. declare interface methods
    1. declare main method
    1. declare private / public functions

Also if should we avoid adding the type name to types (Report instead of IReport or ReportInterface…)?

How to make types and interfaces reusable, can we put interfaces and types in a external packages for reusing them different go files by importing?

Any other recommendations for organizing code (folders structure, file naming, package naming…)?

You can take a look at Uber style guide for Go language: https://github.com/uber-go/guide/blob/master/style.md

It has a lot of good practices to organize your code, generally.

1 Like