类型转换

//string转成int: 
int, err := strconv.Atoi(string)
//string转成int64: 
int64, err := strconv.ParseInt(string, 10, 64)
//int转成string: 
string := strconv.Itoa(int)
//int64转成string: 
string := strconv.FormatInt(int64,10)
//转载:https://blog.csdn.net/iamlihongwei/article/details/79550958

字符串

func main() {
	// Contains判断是否包含关键字
	fmt.Println(strings.Contains("hellogo", "hello"))	// true

	// Join组合
	s := []string{"abc", "hello", "panghu"}
	buf := strings.Join(s, "@")	
	fmt.Println(buf)	// 输出abc@hello@panghu

	// Index
	fmt.Println(strings.Index("hellogo", "go"))	// 5
	fmt.Println(strings.Index("hello", "go"))	// -1

	// Split 以指定的分隔符拆分
	buf = "hello@abc@miku@name"
	s2 := strings.Split(buf, "@")
	fmt.Println(s2)	// [hello abc miku name]

	// Trim去掉两头的字符
	v := strings.Trim("  miku   ", " ")
	fmt.Println(v) 	// miku
}

正则匹配

func main() {
	buf := "   abc asc edw aac 000 asc"
	reg := regexp.MustCompile(`a.c`)
	if reg == nil {
		fmt.Println(reg)
		return
	}
	result := reg.FindAllStringSubmatch(buf, -1) // 负一匹配所有
	fmt.Println(result) // [[abc] [asc] [aac] [asc]]

}
func main() {
	buf := "1.11 355 miku 1.34 1.1"

	reg := regexp.MustCompile(`\d\.\d`)

	// 提取关键信息
	result := reg.FindAllString(buf, -1)
	fmt.Println(result)	// [1.1 1.3 1.1]
}

JSON

结构体生成json

import (
	"fmt"
	"encoding/json"
)

type IT struct {
	Company string
	Subjects []string
	IsOK bool
	Price float64
}

func main() {
	s := IT{"itcast", []string{"go", "python", "c++"}, false, 100.00}

	// 编码,生成json文本
	// buf, err  := json.Marshal(s)
	buf, err := json.MarshalIndent(s, "", " ") // 格式化编码
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(buf)) 
	输出 // {"Company":"itcast","Subjects":["go","python","c++"],"IsOK":false,"Price":100}
}

map生成结构体

	// 创建map
	m := make(map[string]interface{}, 4)
	m["company"] = "test"
	m["subjectes"] = []string{"go", "java", "pyton"}
	m["isOk"] = true
	m["price"] = 100.00

	// 编码json
	result, err := json.Marshal(m)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(result))
	// 输出{"company":"test","isOk":true,"price":100,"subjectes":["go","java","pyton"]}

序列化和反序列化

type Person struct {
	Name string
	Age  int
}

func main() {
	p1 := Person{"panghu", 18}
	fmt.Println(p1)
	// 序列化
	b, err := json.Marshal(p1)
	if err != nil {
		fmt.Println("marshal failed err", err)
		return
	}
	fmt.Printf("%#v \n", string(b))

	// 反序列化
	str := `{"name": "panghu", "age": 18}`
	var p2 Person
	json.Unmarshal([]byte(str), &p2)
	fmt.Printf("%#v \n", p2)
}