golang学习笔记(结构体+json)

结构体

结构体等价关系,只有==和!=关系,没有> < 关系,只有字段和属性完全相同,才等价,并且属于同一类型结构体,不同结构体不能比较,每一个不同的指针结构体的地址均不同

type UserInfo struct {
	Name string
	Age int
	Height float32
	EduSchool string
	Hobby []string
	MoreInfo map[string]interface{}
}
//工厂模式:生成对象
func NewUserInfo(name string,age int,height float32,eduSchool string,hobby []string,moreInfo map[string]interface{}) *UserInfo  {
	return &UserInfo{
		name,
		age,
		height,
		eduSchool,
		hobby,
		moreInfo,
	}

}

结构体+方法

//定义结构体
type miniaction struct {
	name string
	router string
	action string
}

func (mini miniaction) getMiniInfo()  {
	fmt.Printf("mini.name=%s,router=%s,mini.action=%s\n",mini.name,mini.router,mini.action)
}
func (this *miniaction)miniInfo()  {
	fmt.Println(this.name,this.action,this.router)
}
func (this *miniaction)getName() string  {
	return this.name
}
func (this *miniaction)setName(name string)  {
	this.name = name
}

结构体赋值

	type integer int

	var intVar integer
	var intVar2 int
	fmt.Println(intVar,intVar2)

	type userInfo struct {
		Name string
		Age int
		hobby []string
		moreInfo map[string]interface{}
	}

	huge := userInfo{
		Name: "奇衡三",
		Age: 18,
		hobby: []string{"电影","唱歌"},
		moreInfo: map[string]interface{}{
			"role":"演员",
			"earnMoney":300000,
		},
	}
	fmt.Println(huge)

	var xiaoming *userInfo
	xiaoming = new(userInfo)
	(*xiaoming).Name= "xiaoming"
	(*xiaoming).Age = 18

	fmt.Println(xiaoming)

	var xiaohong *userInfo = &userInfo{
		"小红",12,[]string{"学习","完"}, map[string]interface{}{"年仅":"五年级"},
	}
	fmt.Println(xiaohong,(*xiaohong))
	mini1 := miniaction{
			name: "获取商品列表",
			router: "productionList",
			action: "productionList()",
	}
	mini1.getMiniInfo()

结构体标签
Tag是结构体的元信息,可以在运行的时候通过反射的机制读取出来。
结构体标签由一个或多个键值对组成。键与值使用冒号分隔,值用双引号括起来。键值对之间使用一个空格分隔。 注意事项: 为结构体编写Tag时,必须严格遵守键值对的规则。结构体标签的解析代码的容错能力很差,一旦格式写错,编译和运行时都不会提示任何错误,通过反射也无法正确取值。

type Skill struct {
	Name string `json:"code,omitempty"`//标签 omitempty过滤空值
	level int
}
type Actor struct {
	Name string `json:"name"`//标签
	Age int
	Skill []Skill
}
func main()  {
	//[6]Skill{.....}数组结构体
	//[]Skill{....}结构体切片
	qihengsan := &Actor{Name: "齐恒三",Age: 18,Skill: []Skill{
		{Name: "JAVA",level: 1},
		{Name: "JAVASCRIPT",level: 1},
		{Name: "GO",level: 0},
	}}
	res, err := json.Marshal(qihengsan)
	if err != nil {
		fmt.Println("失败")
		return
	}
	fmt.Println(string(res))
}
//Student 学生
type Student struct {
 ID int `json:"id"` //通过指定tag实现json序列化该字段时的key
 Gender string //json序列化是默认使用字段名作为key
 name string //私有不能被json包访问
}

注意点

  1. 结构体是值类型
  2. 结构体之间是否可以相互转换?可以转换,前提条件:具有相同的字段(个数,类型,名称)
  3. 结构体可以做为另一个结构体字段的类型
  4. 结构体变量赋值,各字段不在同一行时,最后一个字段必须加逗号
  5. 结构体变量赋值,各字段在同一行时,最后一个字段的逗号可加,可不加
    方法的接收者类型
  6. 值类型,改变的是接收的副本,不改变接收者本身
  7. 指针类型,传递地址,可直接改变
    结构体继承
type Animal struct {
	name string
}

func (animal *Animal) move()  {
	fmt.Println(animal.name ,"会动")
}

type Dog struct {
	*Animal
	clever int
}

func (dog *Dog)wang()  {
	fmt.Println(dog.name,"汪汪")
}
func main()  {
	d1 := &Dog{clever: 100,Animal:&Animal{
		name: "张三",
	}}
	d1.move()
	d1.wang()

}

JSON

package main

import (
	"encoding/json"
	"fmt"
)

type Student struct {
	ID int
	Gender string
	Name string
}
type Class struct {
	Title string
	Student []*Student

}
func main()  {
	//序列化
	class := &Class{
		Title: "计算机班",
		Student: make([]*Student,0,200),
	}

	for i := 0; i < 20; i++ {
		stu := &Student{Name: fmt.Sprintf("stu%d",i),Gender: "男",ID: i}
		class.Student = append(class.Student, stu)
	}
	data,err := json.Marshal(class)
	if err != nil {
		fmt.Println("错误")
		return
	}
	fmt.Printf("%s",data)
	//解码
	jsonstr := `
	{"Title":"计算机班","Student":[{"ID":0,"Gender":"男","Name":"stu0"},{"ID":1,"Gender":"男","Name":"stu1"},{"ID":2,"Gender":"男","Name":"stu2"},{"ID":3,"Gender":"男","Name":"stu3"},{"ID":4,"Gender":"男","Name":"stu4"},{"ID":5,"Gender":"男","Name":"stu5"},{"ID":6,"Gender":"男","Name":"stu6"},{"ID":7,"Gender":"男","Name":"stu7"},{"ID":8,"Gender":"男","Name":"stu8"},{"ID":9,"Gender":"男","Name":"stu9"},{"ID":10,"Gender":"男","Name":"stu10"},{"ID":11,"Gender":"男","Name":"stu11"},{"ID":12,"Gender":"男","Name":"stu12"},{"ID":13,"Gender":"男","Name":"stu13"},{"ID":14,"Gender":"男","Name":"stu14"},{"ID":15,"Gender":"男","Name":"stu15"},{"ID":16,"Gender":"男","Name":"stu16"},{"ID":17,"Gender":"男","Name":"stu17"},{"ID":18,"Gender":"男","Name":"stu18"},{"ID":19,"Gender":"男","Name":"stu19"}]}
	`
	class := &Class{}
	err := json.Unmarshal([]byte(jsonstr), class)
	if err != nil {
		fmt.Println("转换失败")
		return
	}
	fmt.Println(*class)
	fmt.Println(*class.Student[0])
}

面试题

package main
import "fmt"
type student struct {
	id int
	name string
	age int
}
func demo(ce []student) {
	//切片是引用传递,是可以改变值的
	ce[1].age = 999
	// ce = append(ce, student{3, "xiaowang", 56})
	// return ce
}
func main() {
	var ce []student //定义一个切片类型的结构体
	ce = []student{
		student{1, "xiaoming", 22},
		student{2, "xiaozhang", 33},
	}
	fmt.Println(ce)
	demo(ce)
	fmt.Println(ce)
	//[{1 xiaoming 22} {2 xiaozhang 33}]
	//[{1 xiaoming 22} {2 xiaozhang 999}]
}

//实现map的有序输出
	mapha := make(map[int]string,5)
	mapha[1] = "aaaaaaaaa"
	mapha[2] = "bbbbbbbbb"
	mapha[3] = "ccccccccc"
	mapha[4] = "ddddddddd"
	mapha[5] = "eeeeeeeee"
	for k,v := range mapha{//map是无序的,默认无序输出
		fmt.Println(k,v)
	}
	slice1 := []int{}
	for k,_ := range mapha{
		slice1 = append(slice1,k)
	}
	sort.Ints(slice1)
	for i := 0; i < len(mapha); i++ {
		fmt.Println(mapha[slice1[i]])

	}

匿名结构体

// 定义手机屏幕
type Screen struct {
	Size float32 // 屏幕尺寸
	ResX, ResY int // 屏幕水平和垂直分辨率
}
// 定义电池
type Battery struct {
	Capacity int // 容量
}
// 生成json数据
func genJsonData() []byte {
	// 完整数据结构
	raw := &struct {
		Screen
		Battery
		HasTouchID bool // 序列化时添加的字段:是否有指纹识别
	}{
		// 屏幕参数
		Screen: Screen{
			Size: 5.5,
			ResX: 1920,
			ResY: 1080,
		},
		//电池参数
		Battery: Battery{
			2910,
		},
		//
		// 是否有指纹识别
		HasTouchID: true,
	}

	// 将数据序列化为json
	jsonData, _ := json.Marshal(raw)
	return jsonData
}


func main() {
	// 生成一段json数据
	jsonData := genJsonData()
	fmt.Println(string(jsonData))
	// 只需要屏幕和指纹识别信息的结构和实例
	screenAndTouch := struct {
		Screen
		HasTouchID bool
	}{}
	// 反序列化到screenAndTouch
	json.Unmarshal(jsonData, &screenAndTouch)
	// 输出screenAndTouch的详细结构
	fmt.Printf("%+v\n", screenAndTouch)
	// 只需要电池和指纹识别信息的结构和实例
	batteryAndTouch := struct {
		Battery
		HasTouchID bool
	}{}
	// 反序列化到batteryAndTouch
	json.Unmarshal(jsonData, &batteryAndTouch)
	// 输出screenAndTouch的详细结构
	fmt.Printf("%+v\n", batteryAndTouch)
}

你可能感兴趣的:(golang,golang,json)