paint-brush
An Introductory Guide to Variables and Data Types in Goby@developeraspire
413 reads
413 reads

An Introductory Guide to Variables and Data Types in Go

by Franklin OkolieJanuary 5th, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

An Introductory Guide to Variables and Data Types in Go. Go is all about types, type is Go and Go is type. We will be learning about Go variables and the different data types associated with Go. In this article, we will be using the Go Playground to learn and practice this example. We are going to look at: How to declare a variable in Go, how to declare variables in Go and how to use the short declaration method. How to use Go's Playground.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - An Introductory Guide to Variables and Data Types in Go
Franklin Okolie HackerNoon profile picture

Hello there! So today we will be learning about Go variables and the different data types associated with Go.

Just in case you are just started the Go language, you should read this.

We would be using the Go Playground to learn and practice this example, and you can grab a pop-corn, this would be a long and interesting ride. Ready? Let hop in.

Go is all about types, type is Go and Go is type. - Bill Kennedy

What Will You Learn?

In this article, we are going to look at:

  • How to declare a variable in Go.
  • A different way to declare a variable in Go.
  • The basic types in Go.

And after this article, you will get in-depth understanding of data types in Go.

Drop by drop the bucket gets filled - Todd Mcleaon.

Variables:

Let's look at the code snippet below:

package main

import (
	"fmt"
)

func main() {
        var name string = "Franklin"
        var number int = 34
	fmt.Println("Hello, playground")
}

The above is what your Go playground should look like, now let analyze what is happening there.

  • Package main - Go programs are made of packages for ease of programming and efficient compilation.

The main package is a package provided by Go that is used with the programs to show that they are executable. The package main is the entry point of the Go compiler to know that the file is ready to be executed and complied.

  • import "fmt" - This is a standard libary provided by the Go language for Formatting (I/O functions to print output),by importing the fmt libary package, Go is able to print and format strings, print messages in the console, write files and also format all other data types available in Go.
  • func main() - This is the entry point of programs used and run in Go. It does not take any parameter or argument, by default the function run and compile any code in between the {} curly brackets. It is known as the Chief function in Go; it was provided in Go by default.
  • fmt.Println - Now remember the Formatting package library we imported earlier in the code above. Now, this is it in action, we are calling it and adding a built function avaliable in the libary package called 'Println' and asking it to print the word 'Hello Playground'.
package main

import (
	"fmt"
)

func main() {
        var name string = "Franklin"
        var number int = 34
	fmt.Println(name)
        fmt.Println(number)
}

Output:

"Franklin"
34

var is the keyword used to declare a VARIABLE( name) to a TYPE(string , int) and assign a VALUE( Franklin,34).

Now see Variables as paper box , and the Type as a certain color the papers in the box should have, storing values with are the papers.

Variables can also be declared using the short declaration method with works only if the variable is declared within a function block. By doing this, we are asking Go to deduce what Type should the value be using the ' : ' and the ' = ' .

Example:

package main

import (
	"fmt"
)

func main() {
        var name := "Franklin"
        var number : = 34
	fmt.Println(name)
        fmt.Println(number)
}

Output:

"Franklin"
34

We also have the Constant method using the

const
keyword. This can be declared and used both in the package level and the function level just like the var.

Example:

package main

import (
	"fmt"
)
 const name = "Franklin"
func main() {
     
        const  number = 34
	fmt.Println(name)
        fmt.Println(number)
}

Output:

"Franklin"
34

When using the "const" and the short declaration method, we didn't have to specify the Type, but Go deduced it. That one of the benefits of using them.

Key take away :

  • VARIABLES are like paper box with papers in it which are VALUES of a certain color which are the TYPE.
  • When using the "const" and short declaration to declare variables, you need not specify the type.
  • The "var" and "const" way of declaring variables can be used anywhere in the code, while the short declaration can only be used in a function block between the{} curly braces.

That is for variables. Try and play around with it and print different stuffs, your name, age, etc.

Data Types:

Now let talk about Go data types. A data type simply means the different ways data are stored across a computer program, this data includes numbers, strings(letters), slices e.t.c. Where and how we store this data is what is called a Data Type.

In Go we have 7 Data types :

  • Method sets
  • Boolean types
  • Numeric types
  • String types
  • Array types
  • Slice types
  • Struct types
  • Pointer types
  • Function types
  • Interface types
  • Map types
  • Channel types

But today we would be looking at the following types:

  • Boolean types
  • Numeric types
  • String types
  • Slice types
  • Struct types
  • Map types

We would discuss the rest in the next series. Trying to keep this as short as possible.

Boolean Types:

Boolean types are data types used to store values that are either "True" or "False". Example :

package main

import (
	"fmt"
)

func main() {
         var isMarried bool = false
         var loveFood bool = true
	fmt.Println(isMarried)
        fmt.Println(loveFood)
}

Output:

false
true

As we noticed Types are declared after the variable names for Go to understand what type of value you want the variable to hold and in this case Boolean.

Numeric Types:

Numeric types come in two kinds, we have the int (interger) which are whole numbers, and float64 which are decimal numbers. These two numeric types are used to hold values that are either whole numbers or decimals.

NOTE: There are more kinds of Numeric types but this article is limited to two.

package main

import (
	"fmt"
)

func main() {
        var x int = 19
        var y float64 = 99.7
	fmt.Println("Hello, playground")
}

Output:

19
99.7

Note that putting a float is a variable that has a Type int would throw errors, vice-versa.

String Types:

Strings types are used to hold values that are letters but are called strings in computer science. They are letters. SIMPLE!

Example:

package main

import (
	"fmt"
)

func main() {
       var myName = "DeveloperAspire"
	fmt.Println(myName)
}

Output:

"DeveloperAspire"

Strings are put in-between " " symbols or the back ticks ` `.

Slice Types:

Slices are types used to group values of the same types. When I want a variable to hold more than one number, I would use a slice type to hold the value. When you go to the market to get groceries, you use a bag to put all of them, and they are all the same.

package main

import (
	"fmt"
)

func main() {
       var names = []string{`Franklin`, `Okolie`, `DeveloperAspire`}
       var num = []int{1, 2, 3, 4}
	fmt.Println(names)
}

Output:

[ `Franklin`, `Okolie`, `DeveloperAspire`]
[1, 2, 3, 4]

From the above code example, we noticed that the type came after the '='. That is how the syntax is declared. The ' [ ] ' is telling Go that this is going to be a list and hold it with this ' [ ]', then the Type(int or string), declared after is telling Go the type of values you want your slice to hold, and the ' { }' is used to hold the values.

Quick Tip:
Slice is like a list, it is used to hold the same type of value which are multiple. It is called an Array in languages like JavaScript.

Map types:

Map types are used to store data that have a Key and Value pair, these are used to store values that make reference to each other. They are used to store data of different types. This is like an Object in other languages like JavaScript.

Let make an example:

package main

import (
	"fmt"
)

func main() {
        var x =map[string]int{
                  "Day" : 30,
                   "Night" : 23,
                   }
          var y =map[int]string{
                  30 : "Day",
                  50 : "Night",
                   }
        
	fmt.Println(x)
        fmt.Println(y)
  }

Output:

map[Day:30 Night:23]
map[30:Day 50:Night]

Now let break it down; from the code snippet above, we can see we used the word "map" to declare the type. Now all those are syntax, how a language is being constructed but we are to understand them and not memorize them.

After the map keyword the ' [ ]' is telling Go that the " Key" of the Map type should be what is passed in-between, it may be an int or string. The next declaration after it which is type int, string, slice e.t.c is telling Go what the Values of the map should be. Lastly, the '{ }' just like the slice is the place holder of the value.

var x =  map= type [ ]= key int= value { }=placeholder

Key take aways:

  • The map holds values that consists of a key-value pair, like "Firstname" : "Franklin".
  • The Key data type is passed inside the [ ].
  • The value data type is declared after the [ ].
  • The { } is the place- holder for the values.

Struct types:

Struct types are the advanced way of writing Maps but there a difference. A struct is a sequence of named elements, called fields, each of which has a name and a type.

See it as a Map type that has its key and value already declared and you can use it multiple times anywhere in your code. We have the Named struct and the Anonymous struct. This is likened to be a Class in JavaScript.

package main

import (
	"fmt"
)

type person struct {
	firstname string
	lastname  string
	age       int
}

func main() {
	var person1 = person{
		firstname: "Perry",
		lastname:  "Jack",
		age:       24,
	}
    var person2 = person{
		firstname: "Mark",
		lastname:  "Honest",
		age:       36,
	}
	fmt.Println(person1)
        fmt.Println(person2)

}

Output:

{Perry Jack 24}
{Mark Honest 36}

As we can see struct types are ways of writing Map in a more advanced, neat, and re-usable way, where you can make a Map of a certain structure and use it anywhere you need it.

Go is all about types, type is Go and Go is type - Bill Kennedy

Now let analyze it. We started by declaring a type using the 'Type' keyword that has a name called 'person' using the underlying type called 'struct', after that between the { } we gave the key a variable name and assigned them a specific type their value should have.

It saved us a lot of strength and time from writing the map twice for 2 people as seen above. We simply declared a variable and assigned it the Named type 'person', and use the key names while putting our own different values for the different person. The above example of a struct is called the Named struct as it has the name 'person'.

Example of anonymous struct type:

package main

import (
	"fmt"
)


func main() {
	var person1 = struct {
	firstname string
	lastname  string
	age       int
}person{
		firstname: "Perry",
		lastname:  "Jack",
		age:       24,
	}
 
	fmt.Println(person1)
}

Output:

{Perry Jack 24}

The anonymous struct does not need a name as it is used right when the variable is declared. This is used in most cases when a struct is unique in a code. But why not use a map instead of for clearer code.

The use of Struct proves the 3 chief purposes of Go which are: efficient compilation, efficient execution, and ease of programming. Yes... ease of programming.

Key take aways:

  • Named Struct is declared by using the 'type' keyword and giving it a name with the underlying type 'struct'.
  • The Key variables are already named while the Type of the value has been given.
  • Use the struct by using its name in a variable and passing the preferred value, the Key names CAN NOT be changed.
  • An anonymous struct is a struct without a name.
Go is all about types, type is Go and Go is type. - Bill Kennedy.

You must have seen this quote all over this article right?. That quote was said by Bill Kennedy; one of the Pros of Go. It means that Go is all about type and how to use them efficiently of concurrency, speed, and memory management, once you understand TYPES in Go, you can use it to make program in Go.

That was a long article, right? But that not all we still have more types to discuss but it would be on a different article on this series ' Go for Us '. Watch out for the next article for the other Types in Go. See you in the next series.

Also published at https://dev.to/developeraspire/understanding-variables-and-data-types-in-go-2490