douweida2878 2017-03-08 15:17
浏览 16
已采纳

如何防范声明的变量和发现的错误

I have a small issue which I know why it's there but can't find the solution to it.

What happens is I have a variable that won't be used if error occurred and this causes a compiler error.

Code:

func findAll(query string) ([]Result, error) {
    var res *http.Response
    var err error

    if res, err := http.Get("url" + url.QueryEscape(query)); err != nil {
        return []Result{}, err
    }

    defer res.Body.Close()
    var body []byte
    if body, err := ioutil.ReadAll(res.Body); err != nil {
        return [] Result{}, err
    }

    var f FilteredSearch
    err = xml.Unmarshal(body, &f)
    return f.Results, err
}

First issue is in this line :

if res, err := http.Get("url" + url.QueryEscape(query)); err != nil

res declared and not used

Same issue here:

if body, err := ioutil.ReadAll(res.Body); err != nil 

body declared and not used

  • 写回答

1条回答 默认 最新

  • dongzong8110 2017-03-08 15:22
    关注

    You have already declared the two variables on top of your file and, when you use :=, you are re-declaring them. The solution is to use = instead:

    if res, err = http.Get("url" + url.QueryEscape(query)); err != nil {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)