I’ll explain how to call a function which rests in a different Go file under different package.
A Golang file structure example;
As you see you have a main project folder, there is your main go file where main function coded and other package directories, other go files under them…Generally other go files under custom packages don’t contain a main function, specific task oriented functions are coded there.
To create an use a structure like this;
- Create your project folder
2. Put your main go code which contains main function under it. This file should start with “package main”
3. Create module inside myproject directory.
go mod init "mymodule"
4. Create other directory(or directories) for other packages. For example;
5. Put your other utility go files which doesn’t contain main function under it. This files should start with “package mypackage”
6. Assume that we have util.go under utils and there is a function MyUtility in it. We need to call this function from main function. We should add “mymodule/utils” inside our main go file’s import part and we can call function with this inside code;
Notice that; only functions beginning with capital letters can be public to other go files. MyUtility function should start with capital letter, if you type myUtility, it would be a private function(only visible to it’s go file)