Skip to main content

Command Palette

Search for a command to run...

Go Lang Basics : A Gopher's guide to another Gopher 🦫

Published
•6 min read
Go Lang Basics : A Gopher's guide to another Gopher 🦫
S

💻 Sahil learns, codes, and automates, documenting his journey every step of the way. 🚀

The Beginning: Why Go was created?

Back in 2007, Google was dealing with huge codebases and complex systems. For example, The majority of compilers were too slow to compile Google’s large codebases in reasonable amount of time. They were using languages like C++ and Java, but both had their issues:

  • C++ was powerful but extremely complicated. It had a long compile time, and managing dependencies was painful.

  • Java was more modern but still had issues with managing external libraries and modules.


The Birth of Gopher

In response to these problems, three engineers at Google—Rob Pike, Robert Griesemer, and Ken Thompson—decided to create a new language called Go (or Golang). Their goals were to:

  • Make a language that was easy to learn.

  • Have fast compilation.

  • Simplify the way dependencies (external libraries) were managed.

Problems I faced while learning Go lang

  1. Working with files

    At first glance, working with files in Go might seem like it’s the same as in other programming languages. However, there are some key differences that can feel a bit limiting.

    In many languages, you can create files with any name and put them in any folder without much thought. But in Go, there are some rules. For example, if you create two files in the same folder that declare a function or variable with the same name, you’ll run into an error saying “main redeclared.” This happens because all the files in the same folder must belong to the same package, and Go doesn’t allow duplicate names within a package.

In this example, we have a folder named Basics, and inside it, we have two files: helloworld.go and variables.go. Everything was fine with the first file, but when I created the second file, variables.go, I encountered an error saying "main redeclared in this block." The code runs fine, as you can see in the terminal, but it still generates an error. Here’s why it happens:

  • In Go, every .go file in the same folder belongs to the same package. When you run a Go program, all files in the directory are compiled together as part of the same package. This means that everything declared in one file is visible and accessible to the other files in the same directory.

  • The main function is special in Go because it’s the entry point of any executable program. When you run a Go program, the Go compiler looks for a main function in the main package. If you have multiple files in the same directory (same package) and more than one file has a main function, Go gets confused. Since Go only allows one main function per package, it throws the “main redeclared in this block” error.


How to solve this problem

  1. Create separate packages:

    If you want to keep both main functions for testing or separate functionalities, you can organize your files into different packages. This means creating subdirectories for each package

     /Basics
         /helloworld
             helloworld.go
         /variables
             variables.go
    
  2. Use only one main function:

    If you want to have multiple functionalities but only one entry point, you can keep one main function in one file and define other functions in the other files.

// In helloworld.go
package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
    printVariables() // Call the function from variables.go
}

// In variables .go 
package main

import "fmt"

// Function to print variables
func printVariables() {
    var x int = 10
    fmt.Println("x:", x)
}

Diving deep to gain a clear understanding

  1. Early days of Go: GOPATH

    Initially, Go used a system called GOPATH. This meant all your Go code and all your libraries had to live inside one directory on your machine. The GOPATH system worked like this:

    • You’d have a folder, let’s say /home/user/go, which was your GOPATH.

    • All your code and the libraries you downloaded from the internet had to live inside this directory.

    • Dependencies were managed in a special src folder inside this GOPATH.

    Home/
    └── go/
        ├── bin/          # Compiled binaries will go here
        ├── pkg/          # Compiled package objects will go here
        └── src/
            └── myproject/
                └── main.go

We had to create a src folder, and then our files would go inside it. This method was simple but not flexible, as many of us prefer to create a separate folder on the Desktop or in an easily accessible location. Hmm…what can be done to skip this situation.

  1. Go Modules to the Rescue

    To solve the problems of GOPATH, Go Modules were introduced in Go 1.11 (in 2018). With Go Modules, you no longer needed to keep your project inside the GOPATH. Now, each project could manage its own dependencies. Here’s how it works:

    • Every Go project can now have its own go.mod file.

    • This file lists all the libraries (dependencies) your project needs and which versions you are using.

    • You can have different projects with different versions of the same library, without any conflicts!

  2. go.sum

    • This file is like a safety net.

    • Every time you download a library, Go checks its authenticity. It stores checksums (a kind of fingerprint for each version of a library) in the go.sum file to ensure that no one has tampered with the libraries you're using.

    • This prevents supply chain attacks, where someone could maliciously change the code in a library without you noticing.

  3. go mod tidy

    • Over time, your go.mod file can accumulate unused dependencies—libraries you imported but never used or removed.

    • Running go mod tidy will clean up your go.mod file, removing any unnecessary dependencies and keeping things tidy and organized.

  4. go mod init

    When you start a new Go project, you can run this command to initialize a go.mod file.

  5. go get

    This is the command to download and install new libraries (modules). It automatically adds them to your go.mod file.

  6. go run

    Allows you to run Go code quickly during development. It compiles the specified Go files, executes them, and then removes the binary once it’s done.

  7. go build

    Compiles the Go source code into an executable binary.


Important format specifiers

SpecifierDescription
%vdefault format
%dintegers
%ffloating numbers
%.2ffloating numbers upto 2 decimal places
%sstring
%Ttype of value
%ccharacters
%qquoted characters or strings
%ttrue/false

It covers all the basic concepts of Go language, and you can refer to the code if needed.


Learning Resource


What’s next?

That's not all! Soon, we’ll dive into more advanced topics in Go, such as Concurrency, Go routines, and Packages. Plus, we'll be applying our learnings by building a multi-tier web app with Go.

Stay tuned for more updates and deeper insights! 🚀


More from this blog

Sahil's Tech Trek đź§—

22 posts