版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1333956
package main
import (
"fmt"
// "path"
// "runtime"
// "os"
// "regexp"
// "strings"
// "time"
"encoding/json"
// "sort"
)
func main() {
Example()
}
type List struct {
Url string
Source string
State string
}
type Person struct {
Name string
Age int
Slices []string //slice
Mapstring map[string]string
StructArray []List //结构体的切片型
MapStruct map[string][]List //map:key类型是string或struct,value类型是切片,切片的类型是string或struct
// Desks List
}
//func (p Person) String() string {
// return fmt.Sprintf("%s: %d", p.Name, p.Age)
//}
// ByAge implements sort.Interface for []Person based on
// the Age field.
//type ByAge []Person
//func (a ByAge) Len() int { return len(a) }
//func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
//func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func Example() {
//map 序列化为json
var m map[string]string = make(map[string]string)
m["Go"] = "No.1"
m["Java"] = "No.2"
m["C"] = "No.3"
fmt.Println(m)
list := []List{
{"upload/1.jpg", "http://a.com/1.jpg", "SUCCESS"},
{"upload/2.jpg", "http://b.com/2.jpg", "SUCCESS"},
}
var mm map[string][]List = make(map[string][]List)
mm["Go"] = list
mm["Java"] = list
// m["C"] = "No.3"
fmt.Println(mm)
people := []Person{
{"Bob", 31, []string{"hello", "apple"}, m, list, mm},
// {"John", 42, []string{"python", "golang"}, m},
// {"Michael", 22, []string{"base", "peach", "pear"},map[string]{"a":"haha"}},
// {"Jenny", 26, []string{"python", "golang", "pear"},map[string]{"a":"haha"}},
}
fmt.Println(people)
// sort.Sort(ByAge(people))
// fmt.Println(people)
b, _ := json.Marshal(people)
fmt.Println(string(b))
// if bs, err := json.Marshal(m); err != nil {
// panic(err)
// } else {
// //result --> {"C":"No.3","Go":"No.1","Java":"No.2"}
// fmt.Println(string(bs))
// }
// Output:
// [Bob: 31 John: 42 Michael: 17 Jenny: 26]
// [Michael: 17 Jenny: 26 Bob: 31 John: 42]
}
//type person struct {
// name string
// age int
//}
//var P person // P现在就是person类型的变量了
//P.name = "Astaxie" // 赋值"Astaxie"给P的name属性.
//P.age = 25 // 赋值"25"给变量P的age属性
//fmt.Printf("The person's name is %s", P.name) // 访问P的name属性.
//除了上面这种P的声明使用之外,还有另外几种声明使用方式:
//1.按照顺序提供初始化值
//复制代码 代码如下:
//P := person{"Tom", 25}
//2.通过field:value的方式初始化,这样可以任意顺序
//复制代码 代码如下:
//P := person{age:24, name:"Tom"}
//3.当然也可以通过new函数分配一个指针,此处P的类型为*person
//复制代码 代码如下:
//P := new(person)