Cloud-oriented Life

Cloud Native Technology Improves Lives

Maps

Go provides another important data type named map which maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key.

Create a map

1
2
3
4
5
6
7
8
9
10
var m map[string]int                // nil map of string-int pairs

m1 := make(map[string]float64) // Empty map of string-float64 pairs
m2 := make(map[string]float64, 100) // Preallocate room for 100 entries

m3 := map[string]float64{ // Map literal
"e": 2.71828,
"pi": 3.1416,
}
fmt.Println(len(m3)) // Size of map: 2
  • A map (or dictionary) is an unordered collection of key-value pairs, where each key is unique.

  • You create a new map with a make statement or a map literal.

  • The default zero value of a map is nil. A nil map is equivalent to an empty map except that elements can’t be added.

  • The len function returns the size of a map, which is the number of key-value pairs.


Warning: If you try to add an element to an uninitialized map you get the mysterious run-time error Assignment to entry in nil map.


Set, Get, Delete, Length keys/values,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
m := make(map[string]float64)

m["pi"] = 3.14 // Set a new key-value pair
m["pi"] = 3.1416 // Update value
fmt.Println(m) // Print map: "map[pi:3.1416]"

v := m["pi"] // Get value: v == 3.1416
v = m["pie"] // Not found: v == 0 (zero value)

_, found := m["pi"] // found == true
_, found = m["pie"] // found == false

if x, found := m["pi"]; found {
fmt.Println(x)
} // Prints "3.1416"

delete(m, "pi") // Delete a key-value pair
fmt.Println(m) // Print map: "map[]"

When you index a map you get two return values; the second one (which is optional) is a boolean that indicates if the key exists.

If the key doesn’t exist, the first value will be the default zero value.

For-each range loop

1
2
3
4
5
6
7
8
9
m := map[string]float64{
"pi": 3.1416,
"e": 2.71828,
}
fmt.Println(m) // "map[e:2.71828 pi:3.1416]"

for key, value := range m { // Order not specified
fmt.Println(key, value)
}

Iteration order is not specified and may vary from iteration to iteration.

  • If an entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced.

  • If an entry is created during iteration, that entry may or may not be produced during the iteration.

Starting with Go 1.12, the fmt package prints maps in key-sorted order to ease testing.

Performance and implementation

Maps are backed by hash tables.

Set, get and delete operations run in constant expected time. The time complexity for the add operation is amortized.

The comparison operators == and != must be defined for the key type.

References

Maps explained: create, add, get, delete · YourBasic Go - https://yourbasic.org/golang/maps-explained/

Go - Maps - Tutorialspoint - https://www.tutorialspoint.com/go/go_maps.htm

Go map - working with maps in Golang - https://zetcode.com/golang/map/

Slices

References

[1] Go Slices: usage and internals - The Go Blog - https://blog.golang.org/slices-intro

[3] Slice | A Tour of Go - https://tour.golang.org/moretypes/7

[2] Go by Example: Slices - https://gobyexample.com/slices

[1] The anatomy of Slices in Go. Slices are like Arrays but they can… | by Uday Hiwarale | RunGo | Medium - https://medium.com/rungo/the-anatomy-of-slices-in-go-6450e3bb2b94

[] Go - Slices - Tutorialspoint - https://www.tutorialspoint.com/go/go_slice.htm

[] Slices in Golang - GeeksforGeeks - https://www.geeksforgeeks.org/slices-in-golang/

[] Go slice - working with slices in Golang - https://zetcode.com/golang/slice/

[] Learning Go — Array, Slice, Map. In this article, we are going to see… | by Madhavan Nagarajan | Level Up Coding - https://levelup.gitconnected.com/learning-go-array-slice-map-934eed320b1c

SliceTricks · golang/go Wiki - https://github.com/golang/go/wiki/SliceTricks

[] Golang Slices Tutorial with examples - golangprograms.com - https://www.golangprograms.com/go-language/slices-in-golang-programming.html

[] Slices/arrays explained: create, index, slice, iterate · YourBasic Go - https://yourbasic.org/golang/slices-explained/

4. Composite Types

Composite types, the molecules created by combining the basic types in various ways. We’ll talk about four such types—arrays, slices, maps, and structs.

Arrays and structs are aggregate types; their values are concatenations of other values in memory. Arrays are homogeneous—their elements all have the same type—whereas structs are heterogeneous. Both arrays and structs are fixed size. In contrast, slices and maps are dynamic data structures that grow as values are added.

Read more »

7. Interfaces

Interface types express generalizations or abstractions about the behaviors of other types. By generalizing, interfaces let us write functions that are more flexible and adaptable because they are not tied to the details of one particular implementation.

Many object-oriented languages have some notion of interfaces, but what makes Go’s interfaces so distinctive is that they are satisfied implicitly. In other words, there’s no need to
declare all the interfaces that a given concrete type satisfies; simply possessing the necessary
methods is enough. This design lets you create new interfaces that are satisfied by existing
concrete types without changing the existing types, which is partic ularly useful for types
defined in packages that you don’t control.

Read more »

amazing_print or awesome_print

AmazingPrint is a Ruby library that pretty prints Ruby objects in full color exposing their internal structure with proper indentation. Rails ActiveRecord objects and usage within Rails templates are supported via included mixins.

Read more »

4. Understanding Ownership

Ownership is Rust’s most unique feature, and it enables Rust to make memory safety guarantees without needing a garbage collector.

In this chapter, we’ll talk about ownership as well as several related features: borrowing, slices, and how Rust lays data out in memory.

Read more »

5. Using Structs to Structure Related Data

A struct, or structure, is a custom data type that lets you name and package together multiple related values that make up a meaningful group.

Structs and enums (discussed in Chapter 6) - https://doc.rust-lang.org/book/ch06-00-enums.html are the building blocks for creating new types in your program’s domain to take full advantage of Rust’s compile time type checking.

Read more »
0%