Go/Golang Basics - Variables and Data types

Go/Golang Basics - Variables and Data types

ยท

3 min read

Basic data types in Go are:int, float,complex,string,bool. Int, Float, and complex are part of the numbers.

We'll start with Integers.There are two categories, One is signed and other is unsigned integers.Signed integers can be negative but unsigned integers are always positive.Signed int is referred as int and Unsigned int as uint.

They are : int8, int16, int32, int64, uint8, uint16, uint32, uint64, int, uint.

Example:

package main

import "fmt"

function main() {

            var lengthOfWire uint16 = 36
            var numberOfChocalates int8 = 10 
            var boxlength uint = 200
            var x int =  -450
}

Next is Floating-Point Numbers. They are of two types float32 and float64.

      var ratingOfTheProduct float32 = 3.5

Finally, the next part is Complex Numbers. Complex numbers are of two types, complex64 and complex128. The in-built function creates a complex number from its imaginary and real part. Complex numbers can be initialized as:

      var x complex64 = complex( 5, 2)
      var y complex128 = complex( 7, 3)

If they are printed then, their output would be:

(5 + 2i)
(7 + 3i)

Boolean: Boolean data type contains only 1 bit of information. It's either 0 or 1. 0 denotes false and 1 denotes true.

They can be initialized as :

     var isCodingFun bool = true

The last data type is a string. A string stores sequence of characters and it must be surrounded with double-quotes. They can be initialized as:

     var text string = "Hi, Welcome to Golang Blog Series"

You can concatenate two strings by using the + operator.

     var nameOfMovie string = "Avengers Endgame "

     var concatStr string = nameOfMovie + "is one of the greatest superhero movies."

Variables

Variables in the Go language hold a value even before we assign anything to it. They are default values. All the numeric variables have 0 as default and string variables have"". Boolean variables have false as default value.

You can declare a variable without stating its type by := (short declaration operator ). For example :


         nameOfMovie := "Avengers Endgame"
         x := 15
         y:= 3.7
         isClimateChangeReal := true

Go also allows us to declare multiple variables in a single line. An Example of that is :

       var x , y = 10,20

       nameOfStreet , sure := "Abbey road" , true 
      //'nameOfStreet' is type 'string' and 'sure' is type 'bool'

That's it for this blog โœ….

For more information, You can always check out the Official documentation. This is the official site ๐Ÿ’ฏ.

If you are new to the Go language and you want to check out more, Below are some resources ๐Ÿ”ฅ.

Resources

  • A full video course on freecodecamp.

  • There's a Course on Codecademy on Go language. You can check it out here.