Book Image

Hands-On Go Programming

By : Tarik Guney
Book Image

Hands-On Go Programming

By: Tarik Guney

Overview of this book

<p>With its C-like speed, simplicity, and power for a growing number of system-level programming domains, Go has become increasingly popular among programmers. Hands-On Go Programming teaches you the Go programming by solving commonly faced problems with the help of recipes. You will start by installing Go binaries and get familiar with the tools used for developing an application. Once you have understood these tasks, you will be able to manipulate strings and use them in built-in function constructs to create a complex value from two floating-point values. You will discover how to perform an arithmetic operation date and time, along with parsing them from string values. In addition to this, you will cover concurrency in Go, performing various web programming tasks, implementing system programming, reading and writing files, and honing many fundamental Go programming skills such as proper error handling and logging, among others. Whether you are an expert programmer or newbie, this book helps you understand how various answers are programmed in the Go language.</p>
Table of Contents (18 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributor
Preface
Index

Converting a map into an array of keys and values


In this section, we are going to see how to convert a map into an array of keys and values. Let's imagine a variable named nameAges that has map, as shown in the following code block, and we map string values to integer values. There are names and ages too.

We need to add a new struct named NameAge and it will have Name as a string and Age as integer. We are going to iterate over our nameAges map now. We'll be using a for loop and when you use a range operator on a map type, it returns two things, a key and the value. So, let's write this code:

package main
import "fmt"
type NameAge struct{
  Name string
  Age int
}
func main(){
  var nameAgeSlice []NameAge
  nameAges := map[string]int{
    "Michael": 30,
    "John": 25,
    "Jessica": 26,
    "Ali": 18,
  }
  for key, value := range nameAges{
    nameAgeSlice = append(nameAgeSlice, NameAge {key, value})
  }

  fmt.Println(nameAgeSlice)

}

On running the preceding code, you'll obtain the following...