Go three Map and String

Yiduo doesn't press on. Learn the recently popular Go language and make notes. Relevant codes and notes are also put on Git, Portal.

MAP

Map declaration

m := map[string]int{"one":1, "two":2, "three":3}
m1 := map[string]int{}
m1["one"] = 1

m2 := make(map[string]int, 10/*Initial Capacity*/)
//Why not initialize len? For slices: = make ([] int, 3, 5) will specify len and give the default value of 0, but semantically Map can't specify the default value, so there is no len

 

Access to Map elements
Differences from other major languages
When the access Key does not exist, it will still return zero value. It is not possible to determine whether the element exists by returning nil. You can use the following method to determine

if v,ok:=m1[3];ok{
  t.Logf("Key 3's value is %d", v)
} else {
  t.Log("Key 3 is not existing.")
}

Where ok is the bool value. When the value exists, ok is true

 

Map traversal

m := map[string]int{"one":1, "two":2, "three":3}
for k,v := range m {
    t.Log(k,v)
}

 

Attach test code:

package my_map

import "testing"

func TestInitMap(t *testing.T){
	m1:=map[int]int{1:1,2:4,3:9}
	t.Log(m1[2])
	t.Logf("len m1=%d", len(m1))
	m2:=map[int]int{}
	m2[4]=16
	t.Logf("len m2=%d", len(m2))
	m3:=make(map[int]int,10)
	t.Logf("len m3=%d", len(m3))

	//cap() cannot be used to find the capacity of map. The following code will report an error: invalid argument m3 (type map[int]int) for capgo
	//t.Logf("len m3=%d", cap(m3))
}

func TestAccessNotExistingKey(t *testing.T){
	m1:=map[int]int{}
	t.Log(m1[1])
	m1[2] = 0
	t.Log(m1[2])

	//The output above is
	/*
		TestAccessNotExistingKey: map_test.go:21: 0
		TestAccessNotExistingKey: map_test.go:23: 0
	*/
	//  But in fact, m1[1] is a nonexistent value, m1[2] is a nonexistent value, but the value is 0. In fact, when the value does not exist, Go will assign a default value
	//The advantage is that there will be no null pointer exception, and the disadvantage is that it needs to judge whether it does not exist or is zero itself. The specific judgment method is as follows:

	if v,ok:=m1[3];ok{
		t.Logf("Key 3's value is %d", v)
	} else {
		t.Log("Key 3 is not existing.")
	}

	m1[3] = 0

	if v,ok:=m1[3];ok{
		t.Logf("Key 3's value is %d", v)
	} else {
		t.Log("Key 3 is not existing.")
	}
}

func TestTraveMap(t *testing.T){
	m1:=map[int]int{1:1,2:4,3:9}
	for key,value := range m1{
		t.Log(key,value)
	}
}

 

Map and factory mode
Map value can be a method
Together with the Dock type interface mode of Go, the factory mode of single method object can be easily implemented


Implement Set
There is no Set implementation in the built-in collection of Go, so map[type]bool can be used

  1. Uniqueness of elements
  2. basic operation

Add element

Determine whether the element exists

Delete element

Number of elements

 

Attach Code:

package map_ext

import "testing"

func TestMapWithFunValue(t *testing.T){
	m:=map[int]func(op int)int{}
	m[1] =func(op int) int {return op}
	m[2] =func(op int) int {return op * op}
	m[3] =func(op int) int {return op * op * op}

	t.Log(m[1](2),m[2](2),m[3](2))
}

func TestMapForSet(t *testing.T){
	mySet:=map[int]bool{}

	//1) Add element
	mySet[1] = true

	n:=1

	//2) Determine whether the element exists
	if mySet[n] {
		t.Logf("%d is existing", n)
	} else {
		t.Logf("%d is not existing", n)
	}

	//3) Deleting elements is similar
	delete(mySet, 1)

	//4) Number of elements
	t.Log(len(mySet))


	// 1 is not existing after deleting element
	if mySet[n] {
		t.Logf("%d is existing", n)
	} else {
		t.Logf("%d is not existing", n)
	}
}

  

character string

character string
Differences from other major languages

  1. string in Go is a data type, not a reference or pointer type, so its zero value is' 'instead of null
  2. String is a read-only byte slice. The len function actually returns the number of bytes contained in a string, which is different from the number of characters contained in a specific string
  3. The byte array of string can hold any data

Unicode and UTF8

  1. Unicode is a character set (code point)
  2. UTF8 is a storage implementation of unicode (rules for converting to byte sequences)

Coding and storage

Character "medium"
Unicode 0x4E2D
UTF-8 0XE4B8AD
string/[]byte [0xE4,0xB8,0xAD]


Common string functions

  1. Strings package https://golang.org/pkg/strings/
  2. Strconv package https://golang.org/pkg/strconv/

 

Attach Code:

package string_test

import "testing"

func TestString(t *testing.T){
	var s string
	t.Log(s)
	t.Log(len(s))

	s = "\xE4\xB8\xA4" //Even non displayable characters can be stored, for example "\ xE4\xBB\xA5" will be displayed in disorder

	t.Log(s)
	t.Log(len(s)) //The output result is 3, but it actually corresponds to a Chinese character 'two'

	// string is a byte slice that cannot be changed, so it cannot be assigned a value
	a := "Hello"
	//A [1] ='3 '/ / error: cannot assign to a[1]go
	t.Log(a)

	b := "in"
	t.Log(len(b)) //Is the number of byte s
	c := []rune(b) //rune can extract unicode from strings, which is a built-in mechanism of Go
	t.Log(len(c))
	t.Logf("in unicode %x", c[0])
	t.Logf("in UTF8 %x", s)
	//The output results of the above four log s are as follows:
	/*
	    TestString: string_test.go:21: 3
		TestString: string_test.go:23: 1
		TestString: string_test.go:24: unicode 4e2d in
		TestString: string_test.go:25: Middle utf8e4b8a4
	*/
}

func TestStringToRune(t *testing.T){
	s:= "The People's Republic of China"
	for  _,c:=range s{
		t.Logf("%[1]c %[1]d",c)
	}

	/*d
		The above operation results are
		    TestStringToRune: string_test.go:38: Zhong20013
			TestStringToRune: string_test.go:38: Hua 21326
			TestStringToRune: string_test.go:38: Person 20154
			TestStringToRune: string_test.go:38: Min 27665
			TestStringToRune: string_test.go:38: 20849 in total
			TestStringToRune: string_test.go:38: And 21644
			TestStringToRune: string_test.go:38: Guo 22269

		Note that the code may be a little awkward. The '% [1] c% [1] d' here actually means to format the first character in the format of% c and the first character in the format of% d
	*/
}

Tags: Go git

Posted on Fri, 26 Jun 2020 23:45:40 -0400 by skippa