func (s *ListProductsService) Run(req *product.ListProductsReq) (resp *product.ListProductsResp, err error) {
// Finish your business logic.
categoryQuery := model.NewCategoryQuery(s.ctx, mysql.DB)
c, err := categoryQuery.GetProductsByCategoryName(req.CategoryName)
resp = &product.ListProductsResp{}
for _, v1 := range c {
for _, v := range v1.Products {
resp.Products = append(resp.Products, &product.Product{
Id: uint32(v.ID),
Name: v.Name,
Description: v.Description,
Picture: v.Picture,
Price: v.Price,
})
}
}
return resp, nil
}
为什么要写
resp = &product.ListProductsResp{}
初始化返回对象: resp
是函数的返回值,它的类型是 *product.ListProductsResp
(ListProductsResp
类型的指针)。在 Go 中,当你声明一个指针变量时,它并不会自动被初始化,默认值是 nil
。因此,必须显式地创建一个 ListProductsResp
实例,并将其赋给 resp
,否则 resp
仍然是 nil
,这会导致程序运行时出现 nil pointer dereference
(空指针解引用)错误。