You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2.3 KiB

Learn Go with Tests

https://quii.gitbook.io/learn-go-with-tests/

Modules and Packages

Go source files can only have one package per directory. This is some "outdated advice" so your mileage may vary. Go 1.22 definitely has more capabilities for packages and how your manage source code. https://dave.cheney.net/2014/12/01/five-suggestions-for-setting-up-a-go-project

  • Name of a package should match the directory name.
  • All lower case, only letters and numbers, NO punctuation.
  • name of a package is part of the name of every public type, const, variable, etc Example: mypkg.MyBuffer. So consider what it looks like to a caller.
  • All files in a package directory must have ethe same package declaration, the exception is test files, _test.go. Test files may declare themselves to be in the same package, but with _test appended to the package declaration. These are known as external tests.
  • packages that are actually commands carry the package main declaration. The name of the command is taken from the name of the packages directory.
  • The go commands; go build, go install, go test, go get, all work with packages, not individual files. go run is the exception to this rule.
  • All packages exist inside a directory tree rooted at $GOPATH/src. Because of this, a packages import path and a packages name are often different. The import path is effectively the full path to your package.
  • In Go, the convention is to include the location of the source code in the packages import path, ie $GOPATH/src/github.com/golang/glog This is not required by the language, it is just a feature of go get.

Testable Examples

https://go.dev/blog/examples

As with typical tests, examples are functions that reside in a packages _test.go files. Unlike normal test functions, though, example functions take no arguments and begin with the word Example instead of Test.

If your code changes so that the example is no longer valid, your build will fail. Note that the example function will not be executed if you remove the comment // Output: 6. Although the function will be compiled, it won't be executed.

By adding this code the example will appear in the documentation inside godoc, making your code even more accessible.

If you publish your code with examples to a public URL, you can share the documentation of your code at https://pkg.go.dev/