好吧,是的,我是 golang 的新手,但不是編碼,我對函數(shù)與 golang 一起工作的方式有點(diǎn)困惑,在這 2 周內(nèi),我有 9 次或 10 次我遇到了與函數(shù)有關(guān)的問題。 . 我不懶惰 我到處尋找例子來激勵我,但它們都在一個 main() 函數(shù)下。我試圖在一個函數(shù)中使用 http.get 并且許多其他函數(shù)每次我們需要使用 http.get 時都會調(diào)用這個函數(shù),這樣我們就不會一遍又一遍地重復(fù)代碼..示例:(這不是實(shí)際代碼)func myfunction(site) []byte { resp, err := client.Get(site) // client is because Im tunneling thing on a proxy TOR and had to create some helpers.. but this is working ok. return resp}func magic(staff) string { // do things and create websiteurl with staff and onther contants site := myfunction(website) contents, err := html.Parse(site.Body) //.... //.... return result}main() { //... stuff happens :)}好吧,錯誤是例如因?yàn)槲也粩喔淖兪挛锊⒌玫讲煌腻e誤?;蛘吒緵]有..但沒有結(jié)果..不能使用resp.Body(類型io.ReadCloser)作為[]byte返回參數(shù)的類型。/gobot.go:71:不能使用站點(diǎn)(類型[]byte)作為html.Parse參數(shù)中的io.Reader類型:當(dāng)我第一次沒有遇到錯誤時,Site.Body 在解析時不會做任何事情......我把幾個調(diào)試打印到 STDOUT,我得到了兩個數(shù)字序列的結(jié)果。所以基本上我如何將查詢的“結(jié)果”從一個函數(shù)返回到原始函數(shù),以便可以解析和使用它?我討厭重復(fù)代碼,因此試圖將重復(fù)代碼保留在一個函數(shù)中,并在需要時調(diào)用它。
1 回答

九州編程
TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超4個贊
myfunction有錯誤的返回類型。而不是[]byte它應(yīng)該返回*http.Response。
func myfunction(site string) *http.Response {
resp, err := client.Get(site)
if err != nil {
log.Fatal(err)
}
return resp
}
- 1 回答
- 0 關(guān)注
- 324 瀏覽
添加回答
舉報
0/150
提交
取消