dsq1982 2016-11-26 20:20
浏览 39
已采纳

Golang-传递和返回变量的最佳做法

I am new to golang, I am trying to create a web project with the julienschmidt/httprouter. I am searching to create a well formatted and well structured project so I have two questions about performances passing and returning value or pointers.
In my case I want to create a function that from the request returns an object so I have created it:

// StoreController
func (storeController *StoreController) New(w http.ResponseWriter, r *http.Request) {
    store, err := utilities.GetStoreFromRequest(r)
    // other stuff
    return
}

// Utilities package
func GetStoreFromRequest(r *http.Request) (*models.Store, error) {
    store := models.Store{}
    err := json.NewDecoder(r.Body).Decode(&store)
    // return a pointer is better than returning an object?
    return &store, err
}

Is it right or it is better to create a store object in the storeController and pass it to the function like:

// StoreController
func (storeController *StoreController) New(w http.ResponseWriter, r *http.Request) {
    store := models.Store{}
    err := utilities.GetStoreFromRequest(r, &store)
    // other stuff
    return
}

// Utilities package
func GetStoreFromRequest(r *http.Request, store *models.Store) error {
    err := json.NewDecoder(r.Body).Decode(store)
    return err
}

The other question is about the pointer, is too paranoid to pass and return always pointers instead of object and errors or not? Thanks

  • 写回答

1条回答 默认 最新

  • drau67562 2016-11-27 04:07
    关注

    It's usually redundant and better to eliminate pointless parameters. In fact, by having it as a parameter it's actually initialized to its nil value. Here are all valid ways to do this:

    func GetStoreFromRequest(r *http.Request) (store *models.Store, err error) {
        err = json.NewDecoder(r.Body).Decode(store)
        return
    }
    
    func GetStoreFromRequest(r *http.Request, store *models.Store) error {
        err := json.NewDecoder(r.Body).Decode(store)
        return err
    }
    
    func GetStoreFromRequest(r *http.Request) (*models.Store, error) {
        var store models.Store // or store := models.Store{}
        err = json.NewDecoder(r.Body).Decode(&store)
        return &store, err
    }
    

    It's usually best practice to keep local variables local--imagine passing a parameter i to be used in a for loop. Doesn't make much sense, right? So for this situation, I'd recommend options 1 or 3 (which are essentially the same execution) and leave the local variable out of the function signature.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合