Cyberithub

Basic Structure And Data Types in Go [Complete Tutorial]

Advertisements

Programming has become a popular skill in recent times due to its application in many areas of our everyday lives. With applications in various fields such as business, education, transportation, engineering, and so on, various programming languages have been created to solve a variety of problems since the first computer was created in 1883.

In this article, we will look at the basics of programming in one of the more recent programming languages: Go (also known as Golang). We will look at the structure of basic programs, basic Golang data-types and converting between basic types in Go. We will work on examples to practicalize each concept to ensure you understand maximally, so grab a cup of coffee at the front of your screens and ride with me.

Advertisements

Prerequisites

In order to follow through this article:

  • You need to have a basic understanding of programming languages.
  • You need to download the Go compiler from the official website and follow the directions to install it based on your operating system being either Windows, MacOS or any of the Linux distributions.
  • You need a code editor like visual studio, atom or sublime text. Alternatively, you can download an Integrated Development Environment (IDE). An IDE is an improved code editor with added qualities customized to help you write and execute codes easier. Goland is the most popular IDE used for developing Go programs.

Basic Structure And Data Types in Go [Complete Tutorial]

Introduction

Also Read: An Introduction to GO Programming Language for Beginners

Advertisements

Lets define a few terms:-

a) Data Types

A data type is a way to represent data that can be processed by the computer in programming languages. Every programming language has the concept of data types to represent, to a computer, how a particular data will be stored and the operations that can be performed on it.

Advertisements

For example, you may want to perform a computation like 54 + 60 and store the result in memory. The computer has to know the type of data 54 and 60 represents to ascertain if they can be added together. The computer will ascertain that each number is an integer through a compiler or interpreter, after which they will be added together and the result will be stored in memory using some amount of bits peculiar to the integer data type.

Also, if we want to perform a computation like 70 - hello, the compiler will infer that the operation is not allowed because 70 is an integer and hello is a combination of characters called string in most programming languages.

Advertisements

 

b) Go Programming Language

Go, also known as Golang, is a programming language developed by Rob Pike, Robert Griesemer and Ken Thompson at Google in 2009. It is a statically typed and compiled language with a lot of similarities to older languages like C and C++. Go was created to solve some of the problems and complexities experienced in older programming languages by implementing features such as garbage collection and inbuilt concurrency.

The name “Golang” is a mixture of Go and lang (from language) to create a more distinguished name. It was adopted because of the former domain name of Go, which was golang.org. Through the remainder of this article, I will refer to Go or Golang where suitable, to prevent mixing it up with generic words.

 

c) Basic Structure of Programs in Go

Go was designed to make programming easy for developers by embracing simple syntax and eliminating complexities from other languages. We will look at a basic Hello World program in Go after which we will go in depth into what each line of code does. Spin up your IDE or code editor, create a main.go and write the code below in it. Run the code from a terminal or command line using go run main.go.

NOTE:

All code samples in this article were run on a 64-bit Ubuntu Linux environment.

Basic Structure And Data Types in Go [Complete Tutorial] 2

Output

Basic Structure And Data Types in Go [Complete Tutorial] 3

  • package main is called a package declaration in Golang, i.e defining a package for the program after. It is the most essential part of writing programs in Go because all programs must belong to a particular package. main is the entry package of Golang programs i.e where the compiler begins running code from.
  • Import “fmt” calls an external package to use its functions/methods in the main fmt package contains functions that allows you to format and display data such as Printf, Println, Scanf, etc.
  • func main() { } is a function definition called main is the entry function for Go programs. Within a main package, the compiler looks for a main function to begin running the program from. Therefore, any statement outside the main function will not be executed.
  • Println(“Hello World”) is a function used to print out some data to the console. Println is a function from the fmt package, so we refer to it by prefixing it with fmt. In this statement, we pass alphanumeric characters to the Println function which prints out the data to the console.

 In five (5) lines, we were able to run a Hello World program with syntax that is easy to understand. This indicates the simplicity of Golang and how the developers worked together to make the language as easy to learn for everyone. Before diving into data-types, we will take a brief tour of variables in Go.

 

d) Variables

A variable is an abstract storage entity within a program. It is used to store values so they can be manipulated and/or referenced within a program. Every programming language has the concepts of variables which is very essential when writing applications for efficiency. Go allows variable declaration using the general syntax:

var <identifier> <data-type>

Basic Structure And Data Types in Go [Complete Tutorial] 4

The default value of a variable is the zero-value of its data-type. A variable can be initialized without a data-type and the Go compiler will infer its data-type from its value. Go also allows short variable declaration within functions as a syntactic sugar (i.e to make variable declaration easier)

Basic Structure And Data Types in Go [Complete Tutorial] 5

Output

Basic Structure And Data Types in Go [Complete Tutorial] 6

Short declaration is used when the value a variable will store is known at the time of its declaration within a function. Go doesn’t allow short variable declarations outside a function.

 

Data Types in Go

Just like other programming languages, Go has its specific data types which define how the Go compiler interprets data, performs operations on it and stores them in memory. Data types in Go are divided into four categories: basic types, reference types, aggregate types and interface types. Basic types are integers, floating point, complex numbers, boolean and string, reference types are pointer, map, channel, function and slice, aggregate types are arrays and structs, and interface type represents a single data type called interface.

In the scope of this article, we will look at basic data types only. Basic data types can further be categorized into three types: Numbers, Boolean and Strings.

a) Numbers

In Mathematics, there are different types of numbers used to perform numerous calculations. Go recognizes these types to represent data of all numeric types in code, therefore numbers are further subdivided into three categories: Integers, floating points and complex numbers.

 

i) Integers

Integers represent whole numbers. A computer stores data in bits, and the size of an integer variable determines how many bits is needed to represent it in my memory. The word used to define an integer is int.

Basic Structure And Data Types in Go [Complete Tutorial] 7

In the code above, we declare the variable id as an integer.

In Go, there are two types of integers: Signed and Unsigned Integers.

Signed Integers

Variables declared as signed integers can hold both negative and positive integers. There are five types of signed integers defined based on their size in bits:

int8: 8 bits signed integer, can hold values between -27 to 27-1

int16: 16 bits signed integer, can hold values between -215 to 215-1

int32: 32 bits signed integer, can hold values between -231 to 231-1

int64: 64 bits signed integer, can hold values between -263 to 263-1

int: can either be 32 bits in a 32-bit computer or 64 bits in a 64-bit computer, and will then act like int64 or int32 respectively.

The default data type of an integer variable is int. A rune is a synonym of int32.

Basic Structure And Data Types in Go [Complete Tutorial] 8

Output

Basic Structure And Data Types in Go [Complete Tutorial] 9

 

Unsigned Integers

 Variables declared as unsigned integers can hold only positive numbers. There are also five types of unsigned integer data types:

uint8: 8 bits unsigned integer, can hold values between 0 to 28-1

uint16: 16 bits unsigned integer, can hold values between 0 to 216-1

uint32: 32 bits unsigned integer, can hold values between 0 to 232-1

uint64: 64 bits unsigned integer, can hold values between 0 to 264-1

uint: can either be 32 bits in a 32-bit computer or 64 bits in a 64-bit computer, and will then act like uint32 or uint64

A byte is a synonym of uint8.

The following example investigates the size of each integer data type

Basic Structure And Data Types in Go [Complete Tutorial] 10

Output

Basic Structure And Data Types in Go [Complete Tutorial] 11

The binary.Size() function above returns the size of each variable in bytes (8 bits = 1 byte), so the result is multiplied by 8 to give the size of each variable in bits.

Binary operations like addition, subtraction, multiplication and division can be performed on two or more variables of the same type, otherwise, the compiler will throw an error.

Basic Structure And Data Types in Go [Complete Tutorial] 12

Output

Basic Structure And Data Types in Go [Complete Tutorial] 13

 

ii) Floating Points

Floating point data types are used to represent positive and negative numbers with a decimal point like 34.5, 67.433, -3.09 etc. In Go, floating point is divided into 2 categories: float32 and float64 defined according to IEEE 754 specification. float32 has 6 digits of precision after the decimal point while float64 has about 15 digits. It is advised to use float64 for calculations because float32 can accumulate lots of errors overtime, unless used with extreme care. The default type of a floating point value is float64, and its default value is 0.

Basic Structure And Data Types in Go [Complete Tutorial] 14

Output

Basic Structure And Data Types in Go [Complete Tutorial] 15

Float values can also be represented in exponential form as in 3.4545e25, which is the same as 3.4545 x 1025  This form can be used to represent large float values with accuracy. The limits of float values can be found in the math package. The constants math.MaxFloat32 and math.MaxFloat64 returns the upper limit of float32 and float64 respectively. The minimum values are around 1.4e-45 and 4.9e-324 respectively. There are also special float values like -Inf and +Inf which represents extremely large and small numbers; it is a result of dubious division by a float zero value.

Basic Structure And Data Types in Go [Complete Tutorial] 16

Output

Basic Structure And Data Types in Go [Complete Tutorial] 17

 

iii) Complex Numbers

Go provides two types of complex numbers namely complex64 and complex128 whose components are float32 and float64 respectively. A complex number is made of a real and imaginary part. Go has a built-in function named complex to which you can pass in two float64 values to create a complex number of type complex128.

Basic Structure And Data Types in Go [Complete Tutorial] 18

Output

Basic Structure And Data Types in Go [Complete Tutorial] 19

You can also write a complex number naturally with its constants and use the built-in real and imag functions to return its real and imaginary value.

Basic Structure And Data Types in Go [Complete Tutorial] 20

Output

Basic Structure And Data Types in Go [Complete Tutorial] 21

 

b) Boolean

Boolean variables store only two types, true or false. It is declared with bool. The default value of a boolean variable is false. Using the logical NOT operator, “!” inverts a boolean value.

Basic Structure And Data Types in Go [Complete Tutorial] 22

Output

Basic Structure And Data Types in Go [Complete Tutorial] 23

Boolean variables are used as conditions before running a specific line of code with if-statements, or a for loop iteration. The boolean condition must be true before the if-statement or loop iteration runs. A boolean value is stored as a 1-byte (8 bits) value in memory. Binary logical operations always return a boolean value.

Basic Structure And Data Types in Go [Complete Tutorial] 24

Output

Basic Structure And Data Types in Go [Complete Tutorial] 25

 

c) Strings

A string is an immutable sequence of characters (text), which means after it is defined, it cannot be changed. It is represented with either double quotes (“”) or backticks (``). In Go, a string is a collection of Unicode code points (UTF-8 characters). A string can otherwise be defined as a sequence of bytes with each character occupying at least 1 byte, therefore, its number of bytes will determine the memory to be allocated to it. We can use the built-in len function to get the length or number of bytes of a string. The default value of a string is an empty string (“”)

Basic Structure And Data Types in Go [Complete Tutorial] 26

Output

Basic Structure And Data Types in Go [Complete Tutorial] 27

The index operation s[i] returns the i-th byte of a string s, where 0 <= i < len(s). Converting the byte to a string will return the character as seen in the string. If the index is out the range of s, the compiler panics.

Basic Structure And Data Types in Go [Complete Tutorial] 28

Output

Basic Structure And Data Types in Go [Complete Tutorial] 29

The substring operation s[i:j] returns a string from the original string s containing the character in index i up until j, but excluding j. The compiler returns a panic if any of the index is outside the range of s. Either index i or j can be omitted and the compiler will interpret it as the start or beginning of the string. Omitting both i and j will return the original string.

Basic Structure And Data Types in Go [Complete Tutorial] 30

Output

Basic Structure And Data Types in Go [Complete Tutorial] 31

Within a double quoted string literal, escape sequences that begin with a backslash, \ can be used to insert arbitrary characters into a string. We have used the “\n” escape sequence in Printf statements in many of the code samples above to insert a newline character. Other escape sequences are “\t” to insert a tab, “\r” is carriage return, and “\v” inserts a vertical tab. A backtick string does not support escape sequences and can store strings spanning multiple lines.

Basic Structure And Data Types in Go [Complete Tutorial] 32

Output

Basic Structure And Data Types in Go [Complete Tutorial] 33

 

Converting between Data Types

Go allows conversion between related types such as conversion between the different integer types and float types. The value of a variable can be truncated when converting from a higher type to a lower one if not done with care.

Basic Structure And Data Types in Go [Complete Tutorial] 34

Output

Basic Structure And Data Types in Go [Complete Tutorial] 35

Converting from a float to an integer causes it to lose the values after the decimal point. A string can also be converted to a slice of bytes (we will look at slices in a subsequent article).

Basic Structure And Data Types in Go [Complete Tutorial] 36

Output

Basic Structure And Data Types in Go [Complete Tutorial] 37

 

Conclusion

Go is a statically typed language, which means that the data type of each variable must be known before compilation. Understanding the basic data types in Go allows programmers to design efficient applications and is the foundation of most of the other data types in Go like arrays, slices, maps and structs.

Leave a Comment