Beginners guide to Go-Lang | Part1

  • Anatomy of GO program.
  • Tools available in GoLang.
  • Numbers and Variables in Go.
  • Conditional Operators in Go.
  • Iteration / Loops in Go.
  • Slices in Go.
  • Maps in Go.
  • Functions in Go.
  • Call by Value in Go.
  • Call by Reference in Go.
  • Usage of Pointers in Go.
  • Error Handling and Panic in Go.
  • Usage of Defer keyword in Go.
  • External http Call from Go.
  • Usage of struct in Go.
  • Demonstrating the usage of “new()” in Go.
  • Concept of Constructors in Go.
  • Demonstrating the Example of Object with constructors.
  • Coding to Interfaces.
  • The first line is a comment. You can either use single-line comments, like this, or multi-line comments, which start with a forward slash and an asterisk and end with an asterisk and a forward slash, very much like C++ or Java.
  • Line three is package main. Go code is organised in packages. This helps in big projects, allowing teams to work on parts of the system independently. The main package has a special meaning in Go and it will make your code compile for an executable and not the package.
  • Line five is an import statement. Go is a very simple language, and by itself, does not have many built-in functions. Most of the code you’ll be using will be in packages. Go comes with a start library which contains many packages.
  • In line six, we import the fmt package. The fmt package contains functions for formatted printing.
  • In line nine we have function main. We define a function with the func keyword. The body of the function is enclosed in curly braces. The function main also has a special meaning in Go. It will be executed by the Go runtime when the program starts.
  • The println function from the fmt package prints its argument in a new line. You need to prefix the function name println with the package it came from.
  • Unlike C++ or Java, you don’t need to place a semicolon at the end of the line. The message printed out is a string. Strings in Go starts and end with double quotes.
  • Go strings are Unicode, which means you don’t need special code to support non-English languages.
  • To compile your program and then run it.
  • By design, the Go compiler is fast, go run works quickly and enables fast development cycles. Let’s clear the screen.
  • This is done with the go build command. Go build Welcome.go. And Enter. You created a file called welcome.
  • On Windows, it will be welcome.exe. And if you run it, welcome, you will see the same output for our program. Let’s clear the screen again.
  • test → It will run the tests. Go has a built-in test suite. Test can also run benchmarks so you’ll be able to measure performance of your code.
  • get → It is for installing third-party packages. If you need to connect to a database, pass file format such as yaml.
  • fmt → It will format your code. Most editors run fmt upon save. This eliminates these long and boring discussions about code format. There are many other commands and with time, you’ll probably use more of them. Modern IDEs such as Visual Studio Code or Golang will run a lot of the Go tool commands for you.
  • We declare two variables, x and y, of type int. And unlike C or Java, the type comes after the variable name. In Go, you have int8, int16, int32, int64, and the unsigned versions of all of them. The int type, without size, depends on the system you are using, and is the one you will usually use.
  • If you don’t assign a value to a variable, Go will assign the zero value for this type. In this case, it will be zero value @ lines 9 and 10.
  • In lines 12 and 13, we assign values to x and y.
  • In line 15 and 16, we use fmt.Printf. The Printf function gets a template to print and then a value to fill this template. The %v verb will print a Go object and the %t verb will print its type.
  • In line 18, we define mean and in line 19, we assign the value of x plus y divided by two. And in line 20, again we print the value of mean and its type.
  • Since here, both x and y have type as integer, therefore the type of result is also integer. The result is 1, not 1.5 as expected. The reason is that integer division returns an integer.
  • At line nine and change the variable x to float64. There are two kinds of floats in Go, float64 and float32.
  • Go’s type system is very strict. It doesn’t allow to add integer to a float. Therefore, both the variables @ line 9 and 10, have been converted to float types.
  • Automatic Type Inference → What’s nice about GO is that the compiler can infer the type of variables for you.
  • If you declare a variable but don’t use it, Go will treat this as an error. This might be annoying, but it will protect you from a lot of bugs.
  • In line nine, I’m assigning 10 to the variable x. And then in line 8, I can ask if x is bigger than five. Unlike Java or C++, you don’t need parenthesis around the condition. And if you run it, go run if.go, we’ll see that x is big is being printed out.
  • At line 11 if x is bigger than a hundred, it will print that it’s very big but this is going to be false, so we’ll go to the else section and print that x is not that big.
  • You can use double ampersand for a logical and. So if x is bigger than five and x is smaller than 15, it will print out x is just right. When we run it here, we’ll see that the last statement is x is just right.
  • In the same way that we used double ampersand for and, we can use double pipe for logical or. So we set it, if x is smaller than 20 or x is bigger than 30, we print it x is out of range.
  • If can have an optional initialization statement as well unlike Java. At line 24, We assigned 11 to a and 20 to b, and then we asked, if fraction which is a divided by b, and then semicolon and then asking the condition, is fraction bigger than 0.5, it will print out that a is more than half of b.
  • We start with an initialization statement. In our case it’s just the value of x. And then we list the cases here.
  • In the last switch statement, we get x is small, that is coming from the default statement because, both of above cases have actually failed.
  • At line #26, We are iterating over the elements in the slice, you can use the conditional for loop. We start with zero, up to the length of the loons, and then i++, print the loon.
  • At line #32, as demonstrated, we also have a range keyword.
  • At line #38, If you want both the index and the value, we can use range with a double value context on the left side. So here in line 38 I have both i and name, and then I can print that the name is at a certain position.
  • If you want just the values, we have to use the underscore, as in line 43, because unused variables in Go are a compilation error.
  • Functions in GO can very well return. multiple values too.
  • Functions receive variables and also have return-types defined in definition itself :-
  • Call by ValueWhen Go passes an integer to a function, Go passes it by value which means Go will create a copy of this integer and pass it to the function. Any changes to the integer inside the function won’t affect the original value.
  • Call by ReferenceHowever, when Go passes a slice or a map to a function, it passes it by reference. This means that inside the function body, you’re working with the exact same object that was passed and any changes to the slice you make inside the function stay after the function is over.
  • At line #21, the variable “p” houses the address of an object (which is of type “Point”).
  • At line #15, the address of object, is being received by the variable “p”.
  • At line #22, also note that, “Move()” is a method which is being invoked through a reference variable. Here, the methods are not combined together with the struct class.
  • Here we have an sqrt function, which calculates the square root of a number. But, unlike the one in the math standard library this one will return error on negative numbers.
  • We can see from above method that, we return two values. One is float 64, which is the result, and the other one is of type error.
  • At line #10, we are returning zero, because we have to return some value for the float, but also we are returning a new error.
  • At line #13, we are returning the square root of n and nil. Nil is the value that Go uses to signal nothing. It is very much like null or none in other languages.
  • At line # 7, cleanup() is a function that will free your resource.
  • At line #12, We use a defer code, to free this resource, but note that, first the worker code is executed and only then the the defer’s code is executed. Defer will be work even if you have an error or a panic in your code, making sure that your resources will be freed, in any case.
  • What’s nice about defer is that you write it just after you acquire the resource. This way, you don’t forget to make sure it’s freed. Defer the code in reverse order.
  • At line #12, we are hitting to the external URL, using the http package. We are also catching the response and error from the same.
  • At line #16, we are well using the defer keyword, by the help of which, we indicate that we need to close the ResponseBody, post the processing of this particular method is done.
  • At line #17, we are getting the value of “Content-Type” and it’s an automatic type guessing here.
  • At line #14 above, we have initialised an object of struct type : “Trade”.
  • At line #18 above, it is yet another way of initialising an object of struct type : “Trade”.
  • At line #25 above, note that, an empty object of struct type : “Trade” has been initialised. Therefore, when we print the same, all of it’s attributes have been initialised to the default values.
  • If you’re coming from an object-oriented language, such as Python, Java, C++, and others, you are used to having a constructor or initializer method that is called when an object is created.
  • In Go, you write a function, usually starting with New, that returns a new object. This New function usually returns the pointer to the created object, and optionally, an error value, If it’s possible there was an error creating the object.
  • Here, we are validating the data. For example → If the symbol is empty, we return nil for no object and an error that the symbol can not be empty. We also check the volume, that it’s not negative and we check the price, that it’s not negative.
  • Once we’ve validated the input, we create a pointer to a trade object, and at the end, we return the trade object, and nil, signifying no error.

--

--

--

Software Engineer for Big Data distributed systems

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why Should You Choose MERN Stack Development for Your Web Application?

Race of Abell Survivors

How to Deploy Laravel APP on AWS LightSail with NGINX Instance and Managed MySQL DB

Transfer tab added in PointPay Wallet

Manta Network Squad Game Event: Instructions on How to get on the Whitelist via Discord Bot

Creating a simple Wave spawning system.

How I Structure HTML for better SEO Results

Heroku From the Perspective of a Cloud Architect

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
aditya goel

aditya goel

Software Engineer for Big Data distributed systems

More from Medium

Beginners guide to Go-Lang | Part2

Restful API with Go (Gin)

Use exec.Command to execute a command with a pipe

Consuming an API with Golang