Go - 结构体


本文摘自网络,作者,侵删。

概述

结构体是将零个或多个任意类型的变量,组合在一起的聚合数据类型,也可以看做是数据的集合。

声明结构体

//demo_11.go	
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)	
}

运行结果:

640?wx_fmt=png

生成 JSON

//demo_12.go	
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)	
}

运行结果:

640?wx_fmt=png

改变数据

//demo_13.go	
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))	
}

运行结果:

640?wx_fmt=png



本文来自:51CTO博客

感谢作者:wx6087c7391d3cd

查看原文:Go - 结构体

相关阅读 >>

Golang 内存泄露的原因

Go三色回收

Golang map为啥不并发

这家独角兽旅行服务公司,在用 Go 进行微服务治理

聊聊dubbo-Go-proxy的consulregistryload

Golang依赖注入工具wire指南

手撸Golang 结构型设计模式 适配器模式

Go的值类型和引用类型2——内存分配规则

Gocn酷Go推荐】ip2location 解析 ip 地址库

Golang中的联合体

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...