英文:
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 {
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论