如何防止变量声明和找到错误。

huangapple go评论78阅读模式
英文:

How to guard from variables declared and found error

问题

我有一个小问题,我知道为什么会出现这个问题,但找不到解决办法。

问题是,如果发生错误,我有一个变量不会被使用,这会导致编译错误。

代码:

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
}

第一个问题出现在这一行:

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

res被声明但未使用

同样的问题也出现在这里:

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

body被声明但未使用

英文:

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

得分: 1

你已经在文件的顶部声明了这两个变量,并且当你使用:=时,你正在重新声明它们。解决方案是改用=

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

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 {

huangapple
  • 本文由 发表于 2017年3月8日 23:17:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/42675108.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定