DEV Community

Franklin Okolie
Franklin Okolie

Posted on

Understanding Variables and Data types in Go.

Hello there! So today we would 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 would you learn?

In this article we are going to look at :

  • How to declare a variable in Go.
  • Different way to declare variable in Go.
  • The basic types in Go. And after this article you will get in-depth understanding of types in Go.

Drop by drop the bucket get filled - Todd Mcleaon.

Variables

Let look at the code snippet below:

package main

import (
    "fmt"
)

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

Enter fullscreen mode Exit fullscreen mode

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 compliation. The main package is a package provided by Go that is used with the programs to show that they are excutable. The package main is the entry point of the Go complier to know that the file is ready to be excuted 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 avaliable 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 libary we imported eariler 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)
}
Enter fullscreen mode Exit fullscreen mode

Output :

"Franklin"
34

Enter fullscreen mode Exit fullscreen mode

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 box should have, storing values with are the papers.

rizki-ramadhan-1ZdE_X5Hz3c-unsplash.jpg.

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)
}
Enter fullscreen mode Exit fullscreen mode

Output :

"Franklin"
34

Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

Output :

"Franklin"
34
Enter fullscreen mode Exit fullscreen mode

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 it for variables. Try and play around with it and print different stuffs, your name, age, e.t.c.

### Data Types
Now let talk about Go data types. A data type simply means the different way 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 which 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)
}
Enter fullscreen mode Exit fullscreen mode

Output :

false
true
Enter fullscreen mode Exit fullscreen mode

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 comes in two kinds, we have the int(interger) which are whole numbers and float64 which are decimal numbers. This 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")
}
Enter fullscreen mode Exit fullscreen mode

Output:

19
99.7
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

Output :

"DeveloperAspire"
Enter fullscreen mode Exit fullscreen mode

Strings are put in between " " symbols or the backtick .

Slice Types.

Slices are types used to group values of the same types. When I want a variable to hold more than one numbers, I would use a slice type to hold the value. When you go to the market to get grocries, you use a bag to put all of them and they 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)
}
Enter fullscreen mode Exit fullscreen mode

Output:

[ `Franklin`, `Okolie`, `DeveloperAspire`]
[1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

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 which 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 a 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)
  }
Enter fullscreen mode Exit fullscreen mode

Output :

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

Enter fullscreen mode Exit fullscreen mode

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-bewteen , it may be a int or string. The next declaration after it which is a 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
Enter fullscreen mode Exit fullscreen mode

Key take away

  • The map holdes value that consist 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 different. 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 it key and value already declared and you can use it mulitiple 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)

}
Enter fullscreen mode Exit fullscreen mode

Output :

{Perry Jack 24}
{Mark Honest 36}
Enter fullscreen mode Exit fullscreen mode

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 value for the different person. The above example of struct is called the Named struct as it has 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)
}
Enter fullscreen mode Exit fullscreen mode

Output :

{Perry Jack 24}
Enter fullscreen mode Exit fullscreen mode

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 map instead for clearer code.
The use of Struct proves the 3 chief purpose of Go which are effiecient compilation, effiecient execution and ease of programming. Yes... ease of programming.

Key take away :

  • Named Struct are declared by using the 'type' keyword and giving it a name with the underlying type 'struct'.
  • The Key variables are already named while the values Type have been given.
  • Use the struct by using it name in a variable and passing the preferred value, the Key names CAN NOT be changed.
  • Anonymous struct are struct without 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 made by Bill Kennedy one of the Pro of Go. It means that Go is all about type and how to use them efficeintly of concurreny, 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.

Top comments (0)