An Intro to Data Types and Variables in Go

I decided to spend my time during this worldwide pandemic trying to learn “How to launch a rocket into space” but it’s rather difficult so no. I decided to set my eyes on something more achievable like learning Go (or GoLang) and there is no better way to learn than by documenting your experience of it.

Go is a statically typed programming language meaning that variable types cannot be changed after declaration. This is because the variable needs to be known by the time our code is compiled not when it is executed. Examples of other statically typed languages include C, Java, C++.

Basic Go Data Types

int (alias uint) – represents at least unsigned 32-bit integers (0 to 4294967295)

uint8 (alias byte) – represent unsigned 8-bit integers (0 to 255)

uint16 – represent unsigned 16-bit integers (0 to 65535)

uint32 – represent unsigned 32-bit integers (0 to 4294967295)

uint64 – represent unsigned 64-bit integers (0 to 18446744073709551615)

int8 – represent signed 8-bit integers (-128 to 127)

int16 – represent signed 16-bit integers (-32768 to 32767)

int32 (alias rune) – represent signed 32-bit integers (-2147483648 to 2147483647)

int64 – represent signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

bool – represents true and false only

string – represents human readable data i.e “Hello world”

float32 – represents 32-bit IEEE 754 floating-point number

float64 – represents 64-bit IEEE 754 floating-point number

complex64 – represents complex numbers where both real and imaginary parts are of float32 type

complex128 – represents complex numbers where both real and imaginary parts are of float64 type

side-note: unsigned means that this variable can only represent Zero or Positive numbers

Declaring Variables in Go

Go variables need to be declared before they can be used. It requires that the value assigned to the variable matches the declared variable type. A variable declared as int can not be assigned a string value.

Syntax:

var name type is the syntax to declare a single variable.

var street int declares a variable named street of type int. A name should start with a letter or an _. A name cannot start with a number or be a Go keyword like var.

GOOD variable names include:

  • var street int
  • var _street int

BAD variable names include:

  • var 3treet int
  • var !street int
  • var var int

First Go Program

Let’s declare and run our first Go code!

package main

import "fmt"

func main() {

	var street int
	fmt.Println(street)

}

It returns:

0

Go returns 0 as the value for an initialized int variable. Also, note the order of the statements we declared street variable before trying to use it.

👉 Click here to run the code above in the playground.

0
0

Related Posts