例子1
type firmWareResp struct {Result struct {Code int `json:"code"`Message string `json:"message"`} `json:"result"`Data FirmWareResp `json:"data"`}type FirmWareResp struct {Total int `json:"total"`List []firmWareList `json:"list"`}resp := &firmWareResp{}err := json.Unmarshal([]byte(result), resp)
在上面的例子中,我们在struct中直接定义一个新的结构体,并使用了嵌套组合的用法,利用json unmarshal直接赋值。这种方式是十分简便的,不需要初始化结构体。那假如说我们的匿名结构体(Result)需要初始化呢?
例子2
type Account struct {Id uint32Name stringNested struct {Age uint8}}account := &Account{Id: 10,Name: "jim",Nested: struct{Age uint8}{Age, 20},}//匿名struct直接初始化的时候需要给出结构体//更清晰的使用方法是://acc := new(Account)// acc.Id = 10// acc.Name = "jim"// acc.Nested.Age = 20
例子3
type Handler{}seqNum uint16mx sync.RWMutexlastActive time.Time}// 这里使用了组合,我们在使用Handler结构体的时候,可以直接使用sync.RWMutex这个读写锁,不需要初始化h := Handler{}h.mx.Lock()h.lastActive = time.Now()h.mx.Unlock()
例子4
type ModelListPara struct {Key string `json:"key" form:"key"`QueryPagePara}type QueryPagePara struct {Page int `form:"page" json:"page" binding:""`PageSize int `form:"pageSize" json:"pageSize" binding:""`}var params request.PresignParaerr := c.ShouldBind(¶ms)//这是组合的另外一种用法,我们可以直接定义新的变量,非常简便
例子5
// 我们应该怎么去初始化一个结构体数组呢?我一直都在思考这个问题type AuthRequest struct {Plain stringSame string}requests := []AuthRequest{AuthRequest {"test","test",},}fmt.Println(requests[0].Plain) //成功打印出test
例子6
// 有时候在处理http request的时候,经常会处理一个data的字段,这个字段数据类型回事interface{}, 这样就可以得到不同的data. 这时候我们应该怎么去写呢?不好意思,实现不了...type TerraResp struct {Result struct {Code int `json:"code"`Message string `json:"msg"`Desc string `json:"desc"`} `json:"result"`}type TokenResp struct {Data ObtainTokenRsp `json:"data"`TerraResp}type ObtainTokenRsp struct {CloudName string `json:"cloudName"`AccessKeyID string `json:"accessKeyID"`SecretAccessKey string `json:"secretAccessKey"`SessionToken string `json:"sessionToken"`Region string `json:"region"`CloudBucketName string `json:"cloudBucketName"`CallbackParam string `json:"callbackParam"`StorePath string `json:"storePath"`ExpireTime int64 `json:"expireTime"`}//这种代码的构造方式,已经算是比较优雅的了
