zoukankan      html  css  js  c++  java
  • 基础语法-结构体使用(7)

    总体

    代码

    package main
    
    import (
    	"fmt"
    )
    
    type Person struct {
    	Name string
    	Age int
    }
    
    func main() {
    	var p1 Person
    	p1.Name = "Tom"
    	p1.Age  = 30
    	fmt.Println("p1 =", p1)
    
    	var p2 = Person{Name:"Burke", Age:31}
    	fmt.Println("p2 =", p2)
    
    	p3 := Person{Name:"Aaron", Age:32}
    	fmt.Println("p2 =", p3)
    
    	//匿名结构体
    	p4 := struct {
    		Name string
    		Age int
    	} {Name:"匿名", Age:33}
    	fmt.Println("p4 =", p4)
    }
    
    

    输出

    p1 = {Tom 30}
    p2 = {Burke 31}
    p2 = {Aaron 32}
    p4 = {匿名 33}
    
    

    序列化

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    )
    
    type Result struct {
    	Code    int    `json:"code"`
    	Message string `json:"msg"`
    }
    
    func main() {
    	var res Result
    	res.Code    = 200
    	res.Message = "success"
    
    	//序列化
    	jsons, errs := json.Marshal(res)
    	if errs != nil {
    		fmt.Println("json marshal error:", errs)
    	}
    	fmt.Println("json data :", string(jsons))
    
    	//反序列化
    	var res2 Result
    	errs = json.Unmarshal(jsons, &res2)
    	if errs != nil {
    		fmt.Println("json unmarshal error:", errs)
    	}
    	fmt.Println("res2 :", res2)
    }
    
    

    输出

    json data : {"code":200,"msg":"success"}
    res2 : {200 success}
    

    引用类型使用

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    )
    
    type Result struct {
    	Code    int    `json:"code"`
    	Message string `json:"msg"`
    }
    
    func main() {
    	var res Result
    	res.Code    = 200
    	res.Message = "success"
    	toJson(&res)
    	setData(&res)
    	toJson(&res)
    }
    
    func setData (res *Result) {
    	res.Code    = 500
    	res.Message = "fail"
    }
    
    func toJson (res *Result) {
    	jsons, errs := json.Marshal(res)
    	if errs != nil {
    		fmt.Println("json marshal error:", errs)
    	}
    	fmt.Println("json data :", string(jsons))
    }
    
    
  • 相关阅读:
    【MyEcplise SVN】myEcplise上安装SVN的多种方式
    【微信Java开发 --番外篇】错误解析
    【MyEcplise 插件】反编译插件jad
    maven打包自动配置数据库链接信息
    window.location下的属性说明
    JavaEETest
    java正则过虑字符
    微信小程序开发之大坑记之post请求
    jQuery 获取文件后缀的方法
    java通过解析文件获取apk版本等信息
  • 原文地址:https://www.cnblogs.com/icxldd/p/13777493.html
Copyright © 2011-2022 走看看