summary
A structure is an aggregate data type that combines zero or more variables of any type. It can also be regarded as a collection of data.
Declaration structure
//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)
//Anonymous structure
p4 := struct {
Name string
Age int
}{Name: "anonymous,", Age:33 }
fmt.Println("p4 =", p4)
}
Results of operation:
Generating 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"
//Serialization
jsons, errs := json.Marshal(res)
if errs != nil {
fmt.Println("json marshal error:", errs)
}
fmt.Println("json data :", string(jsons))
//Deserialization
var res2 Result
errs = json.Unmarshal(jsons, &res2)
if errs != nil {
fmt.Println("json unmarshal error:", errs)
}
fmt.Println("res2 :", res2)
}
Results of operation:
Changing data
//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))
}
Results of operation: