英文:
resp declared and not used in golang
问题
每次我尝试运行这段代码时都会出现这个错误。我不确定如何在Go中使用未使用的变量,也不知道如何使代码在不使用未使用的变量的情况下正常工作。为了发布这个问题,我不得不删除一个if-else语句。问题如下:
如果(case1)调用一个URL
否则,如果(case2)调用另一个URL
否则调用另一个URL。
谢谢帮助。我尝试了各种方法,但似乎都不起作用。
package main
import (
"fmt"
"math/rand"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
rage := rand.Int31() % 3
var resp *Response
if rage == 1 {
resp, _ := http.Get("https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurants+in+Sydney&key=AIzaSyAh4t-qlMYrxnk0XF0Yiu9ZXVFDNfPTCFs")
} else {
resp, _ := http.Get("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=cruise&key=AIzaSyAh4t-qlMYrxnk0XF0Yiu9ZXVFDNfPTCFs")
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
resp = unused.Item
fmt.Println("Inside handler")
fmt.Fprintf(w, string(body), nil)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe("localhost:9999", nil)
}
输出:
C:\go\gowiki\websrevice_citibytes_SOAP.go:233: resp declared and not used
C:\go\gowiki\websrevice_citibytes_SOAP.go:235: resp declared and not used
C:\go\gowiki\websrevice_citibytes_SOAP.go:237: resp declared and not used
英文:
I get this error everytime I try to run the code.
I am unsure as to how to use unused variables in go and how to make the code work without using unused variables. I had to delete an if-else statement for this question to be posted. The issue is as such:
if (case1) call one url
else if (case2) call another url
else call another url.
Thanks for the help. I tried various hacks but none of them seem to work.
package main
import (
"fmt"
"math/rand"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
rage := rand.Int31() % 3
var resp *Response
if rage == 1 {
resp, _ := http.Get("https://maps.googleapis.com/maps/api/place/textsearch/json? query=restaurants+in+Sydney&key=AIzaSyAh4t-qlMYrxnk0XF0Yiu9ZXVFDNfPTCFs")
} else {
resp, _ := http.Get("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=cruise&key=AIzaSyAh4t-qlMYrxnk0XF0Yiu9ZXVFDNfPTCFs")
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
resp = unused.Item
fmt.Println("Inside handler")
fmt.Fprintf(w, string(body), nil)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe("localhost:9999", nil)
}
Output:
C:\go\gowiki\websrevice_citibytes_SOAP.go:233: resp declared and not used
C:\go\gowiki\websrevice_citibytes_SOAP.go:235: resp declared and not used
C:\go\gowiki\websrevice_citibytes_SOAP.go:237: resp declared and not used
答案1
得分: 0
你的代码中有几个错误:
var resp *Response
应该改为 var res *http.Response
如果你想使用 ReadAll
函数,你应该导入 io/ioutil
。
resp = unused.Item
是什么意思?应该将其删除。
在你修复了所有这些问题之后,根据其他评论的建议,删除分配给 resp 的行中的 :
:
resp, _ := http.Get("...")
改为 resp, _ = http.Get("...")
错误在于使用 :=
创建了一个新的变量 resp
,它覆盖了之前的变量,并且只在 if 作用域内有效。
正如其他人建议的那样,最好只使用一个字符串变量来存储 URL,并使用 if 条件语句来设置该变量。
var url string = url1
if cond {
url = url2
}
resp, err := http.Get(url)
另外,不要忽略错误。
英文:
There are a few errors in your code:
var resp *Response
should be var res *http.Response
you should import "io/ioutil"
if you want to use its ReadAll
function.
what is resp = unused.Item
? It should be removed.
After you fix all those things, as other comments say: Remove the :
in the lines that assign it to resp:
resp, _ := http.Get("...")
-> resp, _ = http.Get("...")
The error is that using :=
is creating a new variable resp
, that overrides the previous one and only lives inside the if scope.
As others suggested, it may be better to just use a string variable with the url and use the if to set that variable.
var url string = url1
if cond {
url = url2
}
resp, err := http.Get(url)
Also, do not ignore errors
答案2
得分: -1
那些Golang开发团队的奇怪限制真是令人讨厌。
为什么不允许人们通过选项禁用这些限制呢?
答案很简单:他们为自己(为谷歌)编写语言,而不是为社区编写。
幸运的是,Go是开源的,甚至是用Go编写的。
所以,这里有一个简单的补丁,可以移除“声明但未使用”或“声明但未使用”的错误提示:
diff --git a/src/cmd/compile/internal/gc/walk.go b/src/cmd/compile/internal/gc/walk.go
index 770210f..78c0cbc 100644
--- a/src/cmd/compile/internal/gc/walk.go
+++ b/src/cmd/compile/internal/gc/walk.go
@@ -49,10 +49,7 @@ func walk(fn *Node) {
if defn.Left.Name.Used() {
continue
}
- yyerrorl(defn.Left.Pos, "%v declared and not used", ln.Sym)
defn.Left.Name.SetUsed(true) // suppress repeats
- } else {
- yyerrorl(ln.Pos, "%v declared and not used", ln.Sym)
}
}
diff --git a/src/go/types/stmt.go b/src/go/types/stmt.go
index abd9d05..8b15786 100644
--- a/src/go/types/stmt.go
+++ b/src/go/types/stmt.go
@@ -55,6 +55,7 @@ func (check *Checker) funcBody(decl *declInfo, name string, sig *Signature, body
}
func (check *Checker) usage(scope *Scope) {
+ return
var unused []*Var
for _, elem := range scope.elems {
if v, _ := elem.(*Var); v != nil && !v.used {
(适用于go1.12)
将最新的Golang解压到/usr/local/go,并应用此补丁。
然后进行编译:
export GOROOT_BOOTSTRAP=/usr/local/go2
cp -a /usr/local/go /usr/local/go2
cd /usr/local/go/src
sed -e 's#^bash run.bash.*##' -i all.bash
./all.bash
rm -rf /usr/local/go2
unset GOROOT_BOOTSTRAP
与每次处理每个未使用变量相比,每个新版本只需应用一次补丁要快得多。
英文:
Those strange limitations in Golang Devs team heads are terribly annoying.
Why not to allow people to disable their limitations with options?
Answer is simple: they write the lang for themselves (for guugle), not for the community.
Fortunately, Go is OpenSource and even written in Go.
So, here is a simple patch removing the "declared and not used" or "declared but not used" errors raising:
diff --git a/src/cmd/compile/internal/gc/walk.go b/src/cmd/compile/internal/gc/walk.go
index 770210f..78c0cbc 100644
--- a/src/cmd/compile/internal/gc/walk.go
+++ b/src/cmd/compile/internal/gc/walk.go
@@ -49,10 +49,7 @@ func walk(fn *Node) {
if defn.Left.Name.Used() {
continue
}
- yyerrorl(defn.Left.Pos, "%v declared and not used", ln.Sym)
defn.Left.Name.SetUsed(true) // suppress repeats
- } else {
- yyerrorl(ln.Pos, "%v declared and not used", ln.Sym)
}
}
diff --git a/src/go/types/stmt.go b/src/go/types/stmt.go
index abd9d05..8b15786 100644
--- a/src/go/types/stmt.go
+++ b/src/go/types/stmt.go
@@ -55,6 +55,7 @@ func (check *Checker) funcBody(decl *declInfo, name string, sig *Signature, body
}
func (check *Checker) usage(scope *Scope) {
+ return
var unused []*Var
for _, elem := range scope.elems {
if v, _ := elem.(*Var); v != nil && !v.used {
(Actual for go1.12)
Unpack a fresh Golang into /usr/local/go and apply the patch.
Then compile:
export GOROOT_BOOTSTRAP=/usr/local/go2
cp -a /usr/local/go /usr/local/go2
cd /usr/local/go/src
sed -e 's#^bash run.bash.*##' -i all.bash
./all.bash
rm -rf /usr/local/go2
unset GOROOT_BOOTSTRAP
It's much faster to apply the patch once [per new version] than every time deal with every missed variable.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论