thesystemadmin
Published in

thesystemadmin

Golang packages

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;

  1. Create your project folder
mkdir myproject

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;

mkdir utils

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;

utils.MyUtility(...)

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)

--

--

--

A System Admin’s Blog

Recommended from Medium

AZ CLI : Bash script to fetch all azure resources containing pattern or name

What is Jenkins? And Its Use-Cases

Solving BT and BST Coding Problems

Sailing the cloud wave

Ruby on Rails vs NodeJS: Which is the Best Backend Framework

ruby on rails vs nodejs

IOS Dice Rolling App

Java 8 Functional Programming

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
MKM

MKM

More from Medium

Go (Golang): Testing tools & tips to step up your game

AWS Cognito Authentication API for Golang

Level-based logging in Go with Uber Zap

Delve With VSCode To Debug Go App