Getting Started With Golang

Getting Started With Golang

·

6 min read

What's up curious beings! So this is my first blog, I hope you'll learn something from this.

Note: I'm assuming people reading this already know about basic programming jargon and data structures, cause c'mon no one starts with Golang as their first language, if you did please contact me I would like to know what kind of weird environment you grew up in. Jokes aside let's start with the blog.

I'll talk about how you can do basic stuff in Golang the way you do in other languages like executing the program, writing if-else statements, loops, and so on.

Introduction

Golang is an open-source programming language developed by Google to make programmers more productive. It is pretty popular in development and is often used for writing APIs and DevOps tools.

Some info about Go :

  1. Uses a similar syntax to many other languages, including ‘C’.

  2. Produces code that runs fast and uses very little memory.

  3. Run across many platforms.

  4. Provides simple syntax for multi-threaded programs.

  5. Provides some object-oriented features.

  6. Has garbage collection.

How to Compile Code In Go?

If you're familiar with Java and have run Java programs via the command line you'll relate to this, if not you're about to learn something new!

Let's say we have a program like -

COPY

package main

import "fmt"

func main() {
    fmt.Println("Hello World")
}

Before executing the program we need to create an executable file for this program, it can be done via the command go build main.go, or if the file name is helloWorld the command will be go build helloWorld.go

Now to execute this program we simply need to write the command ./main or ./helloWorld.

This whole process will look something like this -

12345678.png

When we type the command ls, we can see our program and its executable file.

But there's a problem here! What if you want to print something else rather than 'Hello World', maybe you want to print ' Hello Humans!'.

You'll have to create a new executable file because the previous one will print 'Hello World!' on execution. This seems like a drag if you want to make several changes to your code, which we usually want to do.

To save the day we have a command go run. Just write the command followed by the file name to execute your program, it'll look like this `go run helloWorld.go'. This command will not create an executable file.

How To Declare And Intialise Variables In Go?

To initialize variables in Go we use the keyword var followed by the variable name and then the variable type.

You can either do

  1. var variableName variableType = value

OR

  1. var variableName variableType variableName = value

OR

  1. variableName := value

In the 3rd representation, Golang recognizes and assigns the type of the variable on its own.

Example -

vars.png

How To Print Stuff In Golang?

If you're actually paying attention here, you would have noticed the term fmt above. It's one of the packages provided by Go. It stands for format and has methods for Input/Output like printf/scanf in C, cout/cin in C++, and println/scanner in Java. It has a method called Println() which we can use to print stuff.

The package also has similar methods like Print(), Printf(), Sprint(), Sprintln() and Sprintf(). But you don't need to care about these right now.

Just know Println() prints in a really nice format, takes care of spaces between multiple statements, and even new lines for every new stuff that needs to be printed. While his little brother Print() just prints in the same line and does not care about taking care of spaces and new line formatting. Typical lil brother...smh.

Let's take an example and see the difference between both :-)

Here's the Code

Print Println.png

Here's the Output

output.png

Yep Println() is actually good.

How To Write If-Else In Golang?

If-Else is pretty different in Golang some might even call it weird.

Points to keep in mind:-

  1. Use of curly brackets is mandatory here even if you're writing a single line of command.

  2. Use of parenthesis (), is optional.

  3. The opening of the curly bracket should not be on the next line. (This is the different or weird part I was talking about).

I think you can understand the first two points, So let's see what this 3rd one is about.

Example -

COPY

// CORRECT
    if true{
        fmt.Println("Hello");
    }else{
        fmt.Println("World");
    }

    // INCORRECT
    if true{
        fmt.Println("Hello");
    }
    else{
        fmt.Println("World");
    }

COPY


    // CORRECT
    if true{
        fmt.Println("Hello");
    }

    // INCORRECT
    if true
    {
        fmt.Println("Hello");
    }

Now what the heck Golang? You just not only want the opening curly bracket in the same line but also the else statement too??

Now, why is that? Why this weird behavior?

Well, the simple answer is that this behavior is related to how Golang deals with the semi-colon and statement grouping. (compiler stuff)

If you want to into depth about this, I would recommend this. This weird behavior is not only limited to if-else statements. Since it's some compiler stuff it can also be seen while writing loops and functions.

How To Write Loops In Golang?

Golang only has for keyword for looping statements, which means no while or do while. Now, this does not mean that we cannot replicate or do the things we do with while and do while. Of course, we just got to be a little creative.

So, here are 4 basic patterns for looping statements-

1. Three-component loop

Now, this is the basic loop format that you would have observed in C, C++, and Java.

COPY

sum := 0
for i := 1; i < 5; i++ {
    sum += i
}
fmt.Println(sum) // 10 (1+2+3+4)

2. While loop

If we skip the initialization and the increment statement from the loop we can get the while loop.

COPY

sum := 0
i := 1
for i < 5 {
    sum += i
    i++;
}
fmt.Println(sum) // 10 (1+2+3+4)

3. Infinite loop

If we somehow forget the condition statement or the increment statement of the loop, we'll get an infinite loop.

COPY

sum := 0
for {
    sum++ // repeated forever
}
fmt.Println(sum) // never reached this line

4. For-each range loop

This pattern is pretty useful when we need to loop over arrays, strings, slices, and maps.

COPY

strings := []string{"hello", "world"} //don't worry about this line is working (its just an array of strings)
for i, s := range strings {
    fmt.Println(i, s)
}

End Of The Blog

Phew, that was some information to process. So this is the end of this blog, I hope you learned something here. Since it was my first blog I would highly appreciate some remarks both positive and negative.

What's The Next Step?

Learning something new sure does take some time. You can't be like oh I read this blog and I'm done now.

  • If you're like this take your stupid ass to this Golang tutorial by "TechWorld With Nana". If you were not like this still go over to that tutorial.

  • After that, you can go over to this video by "FreeCodeCamp" where they teach Golang while creating 11 projects. Now you don't have to create all of them, just create some if you are interested and want some on your resume.

References