package main import "fmt" type Jocongmin struct{ Name string Home string Want string } func (j *Jocongmin) SayName() string{ //这里定义的方法是拓展方法,是对Jocongmin这个struct的继承,也就是struct多了一个Say..方法,可以通过Jocongmin这个struct实例来调用 return "我的名字是"+j.Name } func (j *Jocongmin) SayHome() string{ return "我的家在"+j.Home } func (j *Jocongmin) SayWant() string{ return "我的喜爱是"+j.Want } func main(){ var jocongmin Jocongmin jocongmin.Name="周聪明" jocongmin.Home="福建省" jocongmin.Want="money" fmt.Println(jocongmin.SayName()) //调用了struct的方法 fmt.Println(jocongmin.SayHome()) fmt.Println(jocongmin.SayWant()) }
2.struct的嵌套
package main import "encoding/json" import "fmt" import "strconv" import ( "github.com/drone/routes" "net/http" ) type ResInfo struct { //定义一个struct,然后这个struct里面有哪些子对象 Data YearDataStruct Msg string } type YearDataStruct struct { MouthAll []MouthStruct //定义一个类型为数组的对象,然后这个数组的元素类型为某种struct Sum DetailStruct Average DetailStruct Quarter []QuarterStruct } type DetailStruct struct { One int Two int Three int } type QuarterStruct struct { DetailStruct //可以嵌套复合其他类型的struct,这样就继承下了其他struct的子对象 QuarterNum int } type MouthStruct struct { Mouth int PartmentItem []ItemArrStruct } type ItemArrStruct struct { PartMent string DetailStruct } func cross(w http.ResponseWriter) { w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域 w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型 w.Header().Set("content-type", "application/json") //返回数据格式是json } func main() { fmt.Println("正在启动WEB服务...") var mux *routes.RouteMux = routes.New() mux.Get("/test", DataSend) //http.Handle("/", mux) http.ListenAndServe(":8088", mux) fmt.Println("服务已停止") } func DataSend(w http.ResponseWriter, r *http.Request) { var data YearDataStruct for i := 1; i < 13; i++ { var partMent []ItemArrStruct for t := 1; t < 4; t++ { partMent = append(partMent, ItemArrStruct{ PartMent: "" + strconv.Itoa(t) + "abc", DetailStruct: DetailStruct{ //继承其他struct的子对象的赋值方法是这样的,one two 之类的和partment是同一等级 One: 45, Two: 23, Three: 3432, }, }) } data.MouthAll = append(data.MouthAll, MouthStruct{ Mouth: i, PartmentItem: partMent, }) } for i := 1; i <= 4; i++ { data.Quarter = append(data.Quarter, QuarterStruct{ DetailStruct: DetailStruct{ One: 4324, Two: 23423, Three: 4324234, }, QuarterNum: i, }) } data.Sum = DetailStruct{ One: 4546, Two: 454, Three: 454, } data.Average = DetailStruct{ One: 4546, Two: 454, Three: 465465, } var res ResInfo res.Data = data res.Msg = "right" resJson, _ := json.Marshal(res) fmt.Fprintln(w, string(resJson)) }
有疑问加站长微信联系(非本文作者)