Go Library
Richard Porteous
TL;DR (Too long; Didn’t read)
A quick introduction on how to make and use a ’library’ for and from your code
I found my code for my game was being hidden by the SpriteAtlas code for my game.
Split the code into a new file
I selected the functions, methods, code and data that were specifically for the SpriteAtlas and used refactor and extract to its own file. (using an editor that supports the go plugin)
Manually you can create a spriteatlas.go file. use the same package name and copy your code over. Then you will need to add the required imports to the new file and remove any unnecessary import from your main file. ‘go mod tidy’ may do it for you.
Move The code into its own folder
The next thing you may want to do is to move the code into a sub folder and even possibly make it a subproject using git.
Instead of a sub folder and a subproject lets directly make it a new library
- create a folder at the same level as your app. in this case ‘spriteatlas’
- copy the spriteatlas.go to it and rename it to main.go, and change its package to spriteatlas
- type in ‘go mod init example.com/spriteatlas’ without the quotes and init your mod file
- edit the main. go in the original apps folder and add the import sa “example.com/spriteatlas”
- edit its go.mod file to look like the code below
// Relative path example
replace example.com/spriteatlas => ../spriteatlas
require (
example.com/spriteatlas v0.0.0
)
the top line redirects the ‘address’ for spriteatlas file to point to a local folder
run go mod tidy in both folders.
the app should work as before
NOTE:
Keep the package name consistant (including case) in the mod file and go file(S).
if you run into problems use a quick google search about using ‘golang mod replace’ and ‘golang package
Once you get to a place you want to puvblish your library you would use the full github (for example) path, and would have to publish it witha version number
see