[Go programming learning] dictionary, string

dictionary

How to define a dictionary

var m1 map[string]int //使用字面量创建
m2 := make(map[string]int) //容量使用默认值
m3 := make(map[int]interface{
    
    },100) //使用内置make函数创建,指定容量为100
m4 := map[string]string{
    
    
    "name":"james",
    "age":"35",
}
  • The capacity of the map can be specified without specifying it, and it can be dynamically increased, but if the capacity of the map is known to improve the efficiency of the program, it can also be specified in advance
  • Cannot use incomparable elements as the keys of the dictionary, such as arrays, slices, etc.
  • The value can be of any type. If you use interface{} as the value type, you can accept various types of values, but you need to use type assertions to determine the type when you use it.

Dictionary operation

Dictionary insert element

package main

import  "fmt"

func main(){
    
    
	m1 := make(map[string]string)
	//var m1 map[string]string //使用此方式声明后运行会报错
	//因为声明后并未初始化它,所以它的值是nil, 不指向任何内存地址
	//需要通过make方法分配确定的内存地址。
	m1["key1"] = "v1"
    //m1["key1"] = "v2" //使用相同的key会覆盖
	m1["key2"] = "v2"
	m1["key3"] = "v3"

	fmt.Println(m1["key1"]) //输出v1
    fmt.Println(len(m1)) //输出3
}

Determine whether the key-value pair exists

In some cases, it is not possible to determine whether the key-value pair exists, or whether the current value is stored as a null value. In the Go language, it can be easily judged in the following way:

if value, ok := m1["key4"]; ok {
    
    
	fmt.Println(value)
}

The function of the above code is to retrieve the corresponding value if there is a string with the key name in the current dictionary and return true, otherwise it returns false.

Iterate over the dictionary

for key,value := range m1{
    
    
	fmt.Println(key+","+value)
}

Delete element

delete(m1, "key1")

Store the function as a value in the dictionary

func main() {
    
    
	m := make(map[string]func(a, b int) int)
	m["add"] = func(a, b int) int {
    
    
		return a + b
	}
	m["multi"] = func(a, b int) int {
    
    
		return a * b
	}
	fmt.Println(m["add"](3, 2))
	fmt.Println(m["multi"](3, 2))
}

String

String definition

A string is a value type, and its value is immutable after the string is created.

In the C language, the string is used \0to identify the end of the string, while in the Go language, the length is used to identify the end of the string.

If you want to modify the content of a string, you can convert it to byte slices, and then convert it to a string, but you also need to reallocate memory.

func main() {
    
    
	s := "hello"
	b := []byte(s)
	b[0] = 'g'
	s = string(b)
	fmt.Println(s) //gello
}

If the string contains Chinese, you cannot directly use byte slices to operate on it. This way can be done in go language:

package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
    
    
	s := "hello你好中国"
	fmt.Println(len(s)) //17,每个中文3个字节
	fmt.Println(utf8.RuneCountInString(s)) //9

	b := []byte(s)
	for i := 0; i < len(b); i++ {
    
    
		fmt.Printf("%c", b[i])
	} //输出 helloä½ å¥½ä¸­å�½
	fmt.Println()

	r := []rune(s)
	for i := 0; i < len(r); i++ {
    
    
		fmt.Printf("%c", r[i])
	} //hello你好中国
}

strings package

The strings package provides many functions for manipulating strings. You can see which functions are included here: https://golang.org/pkg/strings/

func main() {
    
    
	var str string = "This is an example of a string"
	//判断字符串是否以Th开头
	fmt.Printf("%t\n", strings.HasPrefix(str, "Th"))
	//判断字符串是否以aa结尾
	fmt.Printf("%t\n", strings.HasSuffix(str, "aa"))
	//判断字符串是否包含an子串
	fmt.Printf("%t\n", strings.Contains(str, "an"))
}

strconv package

The strconv package implements the conversion between basic data types and strings. Here you can see which functions are included: https://golang.org/pkg/strconv/

i, err := strconv.Atoi("-42") //将字符串转为int类型
s := strconv.Itoa(-42) //将int类型转为字符串

If the conversion fails, the corresponding error value is returned

String splicing

SPrintf

const numbers = 100

func BenchmarkSprintf(b *testing.B) {
    
    
	b.ResetTimer()
	for idx := 0; idx < b.N; idx++ {
    
    
		var s string
		for i := 0; i < numbers; i++ {
    
    
			s = fmt.Sprintf("%v%v", s, i)
		}
	}
	b.StopTimer()
}
verb Features
% v Original value output by value
% + v Based on %v, expand the structure field names and values
% # v Output the value in Go language syntax format
%T Output type and value in Go language syntax format
%% Output% body
%b Integers are displayed in binary format
%O Integers are displayed in octal format
%d Integers are displayed in decimal format
%x Integers are displayed in hexadecimal format
%X Integers are displayed in hexadecimal and capital letters
% U Unicode characters
%f Floating point
%p Pointer, display d in hexadecimal format

+Stitching

func BenchmarkStringAdd(b *testing.B) {
    
    
	b.ResetTimer()
	for idx := 0; idx < b.N; idx++ {
    
    
		var s string
		for i := 0; i < numbers; i++ {
    
    
			s += strconv.Itoa(i)
		}
	}
	b.StopTimer()
}

bytes.Buffer

func BenchmarkBytesBuf(b *testing.B) {
    
    
	b.ResetTimer()
	for idx := 0; idx < b.N; idx++ {
    
    
		var buf bytes.Buffer
		for i := 0; i < numbers; i++ {
    
    
			buf.WriteString(strconv.Itoa(i))
		}
		_ = buf.String()
	}
	b.StopTimer()
}

strings.Builder stitching

func BenchmarkStringBuilder(b *testing.B) {
    
    
	b.ResetTimer()
	for idx := 0; idx < b.N; idx++ {
    
    
		var builder strings.Builder
		for i := 0; i < numbers; i++ {
    
    
			builder.WriteString(strconv.Itoa(i))
		}
		_ = builder.String()
	}
	b.StopTimer()
}

Compared

BenchmarkSprintf-8         	   68277	     18431 ns/op
BenchmarkStringBuilder-8   	 1302448	       922 ns/op
BenchmarkBytesBuf-8        	  884354	      1264 ns/op
BenchmarkStringAdd-8       	  208486	      5703 ns/op

It can be seen that splicing strings through strings.Builder is the most efficient.

reference

Guess you like

Origin blog.csdn.net/i0o0iW/article/details/111396293