• Complain

it-ebooks - Golang 101 hacks

Here you can read online it-ebooks - Golang 101 hacks full text of the book (entire story) in english for free. Download pdf and epub, get meaning, cover and reviews about this ebook. year: 2018, publisher: iBooker it-ebooks, genre: Computer. Description of the work, (preface) as well as reviews are available. Best literature library LitArk.com created for fans of good reading and offers a wide selection of genres:

Romance novel Science fiction Adventure Detective Science History Home and family Prose Art Politics Computer Non-fiction Religion Business Children Humor

Choose a favorite category and find really read worthwhile books. Enjoy immersion in the world of imagination, feel the emotions of the characters or learn something new for yourself, make an fascinating discovery.

it-ebooks Golang 101 hacks
  • Book:
    Golang 101 hacks
  • Author:
  • Publisher:
    iBooker it-ebooks
  • Genre:
  • Year:
    2018
  • Rating:
    3 / 5
  • Favourites:
    Add to favourites
  • Your mark:
    • 60
    • 1
    • 2
    • 3
    • 4
    • 5

Golang 101 hacks: summary, description and annotation

We offer to read an annotation, description, summary or preface (depends on what the author of the book "Golang 101 hacks" wrote himself). If you haven't found the necessary information about the book — write in the comments, we will try to find it.

it-ebooks: author's other books


Who wrote Golang 101 hacks? Find out the surname, the name of the author of the book and a list of all author's works by series.

Golang 101 hacks — read online for free the complete book (whole text) full work

Below is the text of the book, divided by pages. System saving the place of the last page read, allows you to conveniently read the book "Golang 101 hacks" online for free, without having to search again every time where you left off. Put a bookmark, and you can go to the page where you finished reading at any time.

Light

Font size:

Reset

Interval:

Bookmark:

Make
Table of Contents
  1. Summary
  2. 1.1
  3. 1.2
  4. 1.3
  5. 1.4
  6. 1.5
  7. 1.6
  8. 1.7
  9. 1.8
  10. 1.9
  11. 1.10
  12. 1.11
  13. 1.12
  14. 1.13
  15. 1.14
  16. 1.15
  17. 1.16
  18. 1.17
  19. 1.18
  20. 1.19
  21. 1.20
  22. 1.21
  23. 1.22
  24. 1.23
  25. 1.24
  26. 1.25
  27. 1.26
  28. 1.27
  29. 1.28
  30. 1.29
  31. 1.30
  32. 1.31
  33. 1.32
  34. 1.33
  35. 1.34
  36. 1.35
  37. 1.36
  38. 1.37
  39. 1.38
  40. 1.39
  41. 1.40
  42. 1.41
  43. 1.42
  44. 1.43
  45. 1.44
Accessing map
Accessing map

Map is a reference type which points to a hash table, and you can use it to construct a "key-value" database which is very handy in practice programming. E.g., the following code will calculate the count of every element in a slice:

package mainimport ( "fmt")func main() { s := []int{1, 1, 2, 2, 3, 3, 3} m := make(map[int]int) for _, v := range s { m[v]++ } for key, value := range m { fmt.Printf("%d occurs %d times\n", key, value) }}

The output is like this:

3 occurs 3 times1 occurs 2 times2 occurs 2 times

Moreover, according to Go spec: "A map is an unordered group of elements of one type, called the element type, indexed by a set of unique keys of another type, called the key type.". So if you run the above program another time, the output may be different:

2 occurs 2 times3 occurs 3 times1 occurs 2 times

You must not presume the element order of a map.

The key type of the map must can be compared with "==" operator: the built-in types, such as int, string, etc, satisfy this requirement; while slice not. For struct type, if its members all can be compared by "==" operator, then this struct can also be used as key.

When you access a non-exist key of the map, the map will return the nil value of the element. I.e.:

package mainimport ( "fmt")func main() { m := make(map[int]bool) m[0] = false m[1] = true fmt.Println(m[0], m[1], m[2])}

The output is:

false true false

the value of m[0] and m[2] are both false, so you can't discriminate whether the key is really in map or not. The solution is to use comma ok method:

value, ok := map[key]

if the key does exit, ok will be true; else ok will be false.

Sometimes, you may not care the values of the map, and use map just as a set. In this case, you can declare the value type as an empty struct: struct{}. An example is like this:

package mainimport ( "fmt")func check(m map[int]struct{}, k int) { if _, ok := m[k]; ok { fmt.Printf("%d is a valid key\n", k) }}func main() { m := make(map[int]struct{}) m[0] = struct{}{} m[1] = struct{}{} for i := 0; i <=2; i++ { check(m, i) }}

The output is:

0 is a valid key1 is a valid key

Using built-in delete function, you can remove an entry in the map, even the key doesn't exist:

delete(map, key)

References:
Effective Go;
The Go Programming Language Specification;
The Go Programming Language.

Array
Array

In Go, the length is also a part of array type. So the following code declares an array:

var array [3]int

while "var slice []int" defines a slice. Because of this characteristic, arrays with the same array element type but different length can't assign values each other. I.E.:

package mainimport "fmt"func main() { var a1 [2]int var a2 [3]int a2 = a1 fmt.Println(a2)}

The compiler will complain:

cannot use a1 (type [2]int) as type [3]int in assignment

Changing "var a1 [2]int" to "var a1 [3]int" will make it work.

Another caveat you should pay attention to is the following code declares an array, not a slice:

array := [...]int {1, 2, 3}

You can verify it by the following code:

package mainimport ( "fmt" "reflect")func main() { array := [...]int {1, 2, 3} slice := []int{1, 2, 3} fmt.Println(reflect.TypeOf(array), reflect.TypeOf(slice))}

The output is:

[3]int []int

Additionally, since in Go, the function argument is passed by "value", so if you use an array as a function argument, the function just does the operations on the copy of the original copy. Check the following code:

package mainimport ( "fmt")func changeArray(array [3]int) { for i, _ := range array { array[i] = 1 } fmt.Printf("In changeArray function, array address is %p, value is %v\n", &array, array)}func main() { var array [3]int fmt.Printf("Original array address is %p, value is %v\n", &array, array) changeArray(array) fmt.Printf("Changed array address is %p, value is %v\n", &array, array)}

The output is:

Original array address is 0xc082008680, value is [0 0 0]In changeArray function, array address is 0xc082008700, value is [1 1 1]Changed array address is 0xc082008680, value is [0 0 0]

From the log, you can see the array's address in changeArray function is not the same with array's address in main function, so the content of original array will definitely not be modified. Furthermore, if the array is very large, copying them when passing argument to function may generate more overhead than you want, you should know about it.

Buffered read
Buffered read

bufio package provides buffered read functions. Let's see an example:

(1) Create a test.txt file first:

# cat test.txtabcdefghijklmn

You can see test.txt contains 4 lines.

(2) See the following program:

package mainimport ( "bufio" "fmt" "io" "log" "os")func main() { f, err := os.Open("test.txt") if err != nil { log.Fatal(err) } r := bufio.NewReader(f) for { if s, err := r.ReadSlice('\n'); err == nil || err == io.EOF { fmt.Printf("%s", s) if err == io.EOF { break } } else { log.Fatal(err) } }}

(a)

f, err := os.Open("test.txt")

Open test.txt file.

(b)

r := bufio.NewReader(f)

bufio.NewReader(f) creates a bufio.Reader struct which implements buffered read function.

(c)

for { if s, err := r.ReadSlice('\n'); err == nil || err == io.EOF { fmt.Printf("%s", s) if err == io.EOF { break } } else { log.Fatal(err) }}

Read and print each line.

The running result is here:

abcdefghijklmn

We can also use bufio.Scanner to implement above "print each line" function:

package mainimport ( "bufio" "fmt" "log" "os")func main() { f, err := os.Open("test.txt") if err != nil { log.Fatal(err) } s := bufio.NewScanner(f) for s.Scan() { fmt.Println(s.Text()) }}

(a)

s := bufio.NewScanner(f)

bufio.NewScanner(f) creates a new bufio.Scanner struct which splits the content by line by default.

(b)

for s.Scan() { fmt.Println(s.Text())}

s.Scan() advances the bufio.Scanner to the next token (in this case, it is one optional carriage return followed by one mandatory newline), and we can use s.Text() function to get the content.

We can also customize SplitFunc function which doesn't separate content by line. Check the following code:

package mainimport ( "bufio" "fmt" "log" "os")func main() { f, err := os.Open("test.txt") if err != nil { log.Fatal(err) } s := bufio.NewScanner(f) split := func(data []byte, atEOF bool) (advance int, token []byte, err error) { for i := 0; i < len(data); i++ { if data[i] == 'h' { return i + 1, data[:i], nil } } return 0, data, bufio.ErrFinalToken } s.Split(split) for s.Scan() { fmt.Println(s.Text()) }}
Next page
Light

Font size:

Reset

Interval:

Bookmark:

Make

Similar books «Golang 101 hacks»

Look at similar books to Golang 101 hacks. We have selected literature similar in name and meaning in the hope of providing readers with more options to find new, interesting, not yet read works.


Reviews about «Golang 101 hacks»

Discussion, reviews of the book Golang 101 hacks and just readers' own opinions. Leave your comments, write what you think about the work, its meaning or the main characters. Specify what exactly you liked and what you didn't like, and why you think so.