Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learn Data Structures and Algorithms with Golang

You're reading from  Learn Data Structures and Algorithms with Golang

Product type Book
Published in Mar 2019
Publisher Packt
ISBN-13 9781789618501
Pages 336 pages
Edition 1st Edition
Languages
Author (1):
Bhagvan Kommadi Bhagvan Kommadi
Profile icon Bhagvan Kommadi

Table of Contents (16) Chapters

Preface 1. Section 1: Introduction to Data Structures and Algorithms and the Go Language
2. Data Structures and Algorithms 3. Getting Started with Go for Data Structures and Algorithms 4. Section 2: Basic Data Structures and Algorithms using Go
5. Linear Data Structures 6. Non-Linear Data Structures 7. Homogeneous Data Structures 8. Heterogeneous Data Structures 9. Dynamic Data Structures 10. Classic Algorithms 11. Section 3: Advanced Data Structures and Algorithms using Go
12. Network and Sparse Matrix Representation 13. Memory Management 14. Next Steps 15. Other Books You May Enjoy

Getting Started with Go for Data Structures and Algorithms

The Go programming language has been rapidly adopted by developers for building web applications. With its impressive performance and ease of development, Go enjoys the support of a wide variety of open source frameworks for building scalable and highly performant web services and apps. The migration to Golang has taken place mainly because of its fast, lightweight, and inbuilt concurrency features. This brings with it the need to learn data structures and algorithms with this growing language.

In data structures, a collection of elements of a single type is called an array. Slices are similar to arrays except that they have unusual properties. Slice operations such as enlarging a slice using append and copy methods, assigning parts of a slice, appending a slice, and appending a part of a slice are presented with code...

Technical requirements

Install Go Version 1.10 at https://golang.org/doc/install, depending on your operating system.

The code files for this chapter can be found at the following GitHub URL: https://github.com/PacktPublishing/Learn-Data-Structures-and-Algorithms-with-Golang/tree/master/Chapter02.

In this chapter, database operations require the github.com/go-sql-driver/mysql package. In addition to this, MySQL (4.1+) needs to be installed from https://dev.mysql.com/downloads/mysql/.

Run the following command:

go get -u github.com/go-sql-driver/mysql

Arrays

Arrays are the most famous data structures in different programming languages. Different data types can be handled as elements in arrays such as int, float32, double, and others. The following code snippet shows the initialization of an array (arrays.go):

var arr = [5]int {1,2,4,5,6}

An array's size can be found with the len() function. A for loop is used for accessing all the elements in an array, as follows:

var i int
for i=0; i< len(arr); i++ {
fmt.Println("printing elements ",arr[i]
}

In the following code snippet, the range keyword is explained in detail. The range keyword can be used to access the index and value for each element:

var value int
for i, value = range arr{
fmt.Println(" range ",value)
}

The _ blank identifier is used if the index is ignored. The following code shows how a _ blank identifier can be used:

for _, value = range...

Slices

Go Slice is an abstraction over Go Array. Multiple data elements of the same type are allowed by Go arrays. The definition of variables that can hold several data elements of the same type are allowed by Go Array, but it does not have any provision of inbuilt methods to increase its size in Go. This shortcoming is taken care of by Slices. A Go slice can be appended to elements after the capacity has reached its size. Slices are dynamic and can double the current capacity in order to add more elements.

Let's take a look at the len function in the next section.

The len function

The len() function gives the current length of slice, and the capacity of slice can be obtained using the cap() function. The following...

Two-dimensional slices

Two-dimensional slices are descriptors of a two-dimensional array. A two-dimensional slice is a contiguous section of an array that is stored away from the slice itself. It holds references to an underlying array. A two-dimensional slice will be an array of arrays, while the capacity of a slice can be increased by creating a new slice and copying the contents of the initial slice into the new one. This is also referred to as a slice of slices. The following is an example of a two-dimensional array. A 2D array is created and the array elements are initialized with values.

twodarray.go is the code exhibit that's presented in the following code:

//main package has examples shown
// in Go Data Structures and algorithms book
package main
// importing fmt package
import (
"fmt"
)
// main method
func main() {
var TwoDArray [8][8]int
TwoDArray[3][6] ...

Maps

Maps are used to keep track of keys that are types, such as integers, strings, float, double, pointers, interfaces, structs, and arrays. The values can be of different types. In the following example, the language of the map type with a key integer and a value string is created (maps.go):

var languages = map[int]string {
3: “English”,
4: “French”,
5: “Spanish”
}

Maps can be created using the make method, specifying the key type and the value type. Products of a map type with a key integer and value string are shown in the following code snippet:

var products = make(map[int]string)
products[1] = “chair”
products[2] = “table”

A for loop is used for iterating through the map. The languages map is iterated as follows:

var i int
var value string
for i, value = range languages {
fmt.Println("...

Database operations

In this section, we will take a look at some of database operations using appropriate examples.

Let's start with the GetCustomer method in the next section.

The GetCustomer method

The GetCustomer method retrieves the Customer data from the database. To start with, the create database operation is shown in the following example. Customer is the table with the Customerid, CustomerName, and SSN attributes. The GetConnection method returns the database connection, which is used to query the database. The query then returns the rows from the database table. In the following code, database operations are explained in detail (database_operations.go):

//main package has examples shown
// in Hands-On Data...

Variadic functions

A function in which we pass an infinite number of arguments, instead of passing them one at a time, is called a variadic function. The type of the final parameter is preceded by an ellipsis (...), while declaring a variadic function; this shows us that the function might be called with any number of arguments of this type.

Variadic functions can be invoked with a variable number of parameters. fmt.Println is a common variadic function, as follows:

//main method
func main() {
var customers []Customer
customers = GetCustomers()
fmt.Println("Before Insert",customers)
var customer Customer
customer.CustomerName = "Arnie Smith"
customer.SSN = "2386343"
InsertCustomer(customer)
customers = GetCustomers()
fmt.Println("After Insert",customers)
}

Run the following commands:

go run database_operations...

CRUD web forms

In this section, we will explain web forms using basic examples, showing you how to perform various actions.

To start a basic HTML page with the Go net/http package, the web forms example is as follows (webforms.go). This has a welcome greeting in main.html:

//main package has examples shown
// in Hands-On Data Structures and algorithms with Go book
package main
// importing fmt, database/sql, net/http, text/template package
import (
"net/http"
"text/template"
"log")
// Home method renders the main.html
func Home(writer http.ResponseWriter, reader *http.Request) {
var template_html *template.Template
template_html = template.Must(template.ParseFiles("main.html"))
template_html.Execute(writer,nil)
}
// main method
func main() {
log.Println("Server started on: http://localhost:8000")
http.HandleFunc...

Summary

This chapter introduced database operations and web forms. Now, you will be able to build web applications that can store data in databases. Arrays, slices, two-dimensional slices, and maps were covered with code samples. Array methods such as len, iterating through an array using for, and range were explained in this chapter using code snippets. Two-dimensional arrays and slice of slices were discussed in the Slices section.

Maps were explained with various scenarios such as adding keys and values, as well as retrieving and deleting values. Maps of different types, such as strings and integers, were also discussed in this chapter. Furthermore, variadic functions, deferred function calls, and panic and recover operations were demonstrated in the Database operations and CRUD web forms sections.

The CRM application was built as a web application with data persisted in the...

Questions

  1. What is the name of the method to get the size of an array?
  2. How do you find the capacity of the slice?
  3. How do you initialize the 2D slice of a string type?
  4. How do you add an element to the slice?
  5. Using code, can you demonstrate how to create a map of key strings and value strings? Initialize the map with keys and values in the code, iterate them in a loop, and print the keys and values in the code.

  1. How do you delete a value in a map?
  2. What parameters are required for getting a database connection?
  3. Which sql.Rows class method makes it possible to read the attributes of the entity in a table?
  4. What does defer do when a database connection is closed?
  5. Which method allows the sql.DB class to create a prepared statement?

Further reading

To read more about arrays, maps and slices, the following links are recommended:

  • Learning Go Data Structures and Algorithms [Video], by Gustavo Chaín
  • Mastering Go, by Mihalis Tsoukalos
lock icon The rest of the chapter is locked
You have been reading a chapter from
Learn Data Structures and Algorithms with Golang
Published in: Mar 2019 Publisher: Packt ISBN-13: 9781789618501
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}