package main
import (
"encoding/json"
"fmt"
)
type Person2 struct {
Name string `json:"name"`
Age int `json:"age"`
Addr string `json:"addr,omitempty"` //omitempty 如果值为空,忽略字段
}
//可以传任意个数,任意类型的参数
func myFunc(items ...interface{}){
for _,item := range items{
//switch i.(type) {
//case int:
// fmt.Println("参数的类型是 int")
//case string:
// fmt.Println("参数的类型是 string")
//}
//interface类型转换为结构体 如果类型不一致,会异常
res, ok := item.(Person2)
if(ok == true){
//转成json打印
data2, err := json.Marshal(res)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", data2)
}
}
}
func main() {
//结构体赋值
p1 := Person2{
Name: "Jack",
Age: 22,
}
data1, err := json.Marshal(p1)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", data1)
//调用方法,可以传任意个数,任意类型的参数
myFunc(p1)
}