Uncategorized

Golang Data Structures

Rune

Strings are made up of “runes” rather than chars. Rather than having char and wchar for characters and unicode characters, a rune is a “code point” as defined in the Unicode standard. Internally it is  a 32-bit representation.

nihao := "你好"
for index, runeVal := range nihao {
 fmt.Printf("Character %#U Byte position %d\n", runeValue, index)
}

String to array of runes

runes := []rune(s)

rune array to string

str := string(runes)

Slice

A slice consists of a pointer to an array segment, length of the segment and its capacity i.e. the maximum length of the segment.

  • Create
b = make([]T, len(a))
  • Add element
var s []int
s = append(s, 1) //add one element 
s = append(s, 2,3,4) //add multiple
s = append(s, s1…) // append another slice
  • Delete
s[len(s)-1] //remove last element
  • Iterate
for index, value := range s {

}
  • Two dimensional slices

Slices are one-dimensional. We have to compose it to form two-dimensional arrays.

matrix := make([][]int, row) 
for m := range matrix { 
     matrix[m] = make([]int, col)
}

When you pass a slice to a function, since it is a pointer to an array you just get a copy of the slice structure. It will still point to the same underlying array segment.

Map

The built-in map type implements a hash table. Map is also a reference type like slices. Maps, like channels, but unlike slices, are just pointers to runtime types. As you saw above, a map is just a pointer to a runtime.hmap structure. So when we declare a map using var, its value will be nil until initialized using make. Attempts to access a nil map will result in a panic.

  • Create
x := make(map[int]int)
  • Add element
x[1] = 10
  • Delete element
delete(x, 1)
  • Find value
val, ok := x[key]
  • Iterating
for key, val:= range x { 
   println("Key:", key, "Value:", val ,"Value:", m[k]) 
}

 

Struct

struct is a collection of fields.

A struct can have methods defined on it. There are two kinds of methods that can be defined on a  struct, a value receiver and a pointer receiver.

type T struct {
	a int
}
func (tv  T) Mv(a int) int         { return 0 }  // value receiver
func (tp *T) Mp(f float32) float32 { return 1 }  // pointer receiver

It all comes down which one is better for the problem at hand.

Pass by value or reference

 

Interesting Reads:

https://dave.cheney.net/2014/03/25/the-empty-struct

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s