Demystifying workspaces and env in go

D

Before actually started writing any code, I should spend some time explaining about these workspaces. This a heavy theory topic, but I still want you to read it. Because these are some of the fundamental things you should know before even started writing the code.

TL;DR

I want to you have some experience in working with terminal to follow along. But if you’re not and don’t want to know this inner-workings of GOLANG, then I want you to understand only one thing

Always create your project in ~/src

(if there’s no src folder in your root directory, create one)

So now for the people who are interested in ‘why should i do that’?

So before explaining anything I want you to create a file(say hi.go) anywhere in your computer but inside a folder named ‘hi’

copy paste the below code to hi.go

//code taken from official website
package main

import "fmt"

func main() {
	fmt.Println("hello, world")
}

Now cd into that directory and type go run hi

You might think it should print hello, world. But you should get a error that will show something like this

Well, in GO, we have something called workspaces.

Go programmers typically keep all their Go code in a single workspace.

A workspace contains many version control repositories (managed by Git, for example).

Each repository contains one or more packages.

Each package consists of one or more Go source files in a single directory.

The path to a package’s directory determines its import path.

(source: official golang docs)

So in a nutshell, workspace is Go’s way to facilitate project management. A workspace in nutshell, is a directory on your system where Go looks for source code files.

First I want you to type go env in your terminal.

That should list all the ENV variables. We are only gonna talk about 3 ENV now.

GOROOT, GOPATH, GOBIN

you can see in default GOPATH="Users/vigneshwar/go" in my case. Go first checks whether ‘hi’ directory exists in GOROOT and then checks GOPATH.

So thats the reason why you should always create your projects in GOPATH(~/go).

I will tell you how to change this ENV and creating your own workspaces in the next article.

Bye.

About the author

vigneshwar

2 comments

Leave a Reply

  • You could simply run your program using command “go run hi.go”. If you use command “go run hi” go will consider “hi” as a package and there is no such package called “hi” neither in your GOPATH nor in GOROOT so you got that error. There are several file structures one could use according to the requirement of the project, src-pkg-bin is one of them.

    • Its my mistake for not clarifying it. Its almost mandatory to create a folder even to write a hello world in vscode. So I thought its natural to do so. In this article I merely stated that there are some path env in GO

      But in the next article I think I explained it well.
      Thanks for reading!

By vigneshwar

Most common tags

%d bloggers like this: