我想要执行函数并在变量上返回输出结果,这是我的实际代码:
package main
import (
"os"
"net/http"
"io"
"fmt"
"strings"
)
func downloadFile(url string) (err error) {
resp, err := http.Get(url)
if err != nil {
return err
}
// extrage numele fisierului din linkul redirectionat.
finalURL := resp.Request.URL.String()
parts := strings.Split(finalURL, "/")
filename := parts[len(parts)-1]
out, errr := os.Create(filename)
if errr != nil {
return errr
}
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
defer out.Close()
defer resp.Body.Close()
return filename
}
func main() {
var url1 string = "https://transfer.sh/5e2iH/test.txt"
var filename2 string = "test test test"
filename2 := downloadFile(url1)
fmt.Println( filename2 )
}
我想执行函数downloadFile并在变量filename2中返回变量filename,返回给我这个错误,我错了吗?我是python开发者,我肯定会犯愚蠢的错误:)
F:\dev\GoLang\gitlab\check>go run download.go
# command-line-arguments
.\download.go:37:3: cannot use filename (type string) as type error in return ar
gument:
string does not implement error (missing Error method)
.\download.go:45:13: no new variables on left side of :=
.\download.go:45:13: cannot use downloadFile(url1) (type error) as type string i
n assignment
答案 0 :(得分:1)
Go是强类型的,因此函数不能返回错误或字符串,具体取决于具体情况。
幸运的是,Go可以从函数中返回两个变量,这是实现所需内容的首选方式。返回一个字符串AND错误,如果没有错误,则返回nil作为错误。
功能签名应为
func downloadFile(url string) (filename string, err error) {
.....
// and since the variables are named in the signature, at the end you can just do:
return
}
调用函数应检查错误和返回的字符串,就像您的代码在调用os.Create(filename)
时所做的那样
答案 1 :(得分:1)
您不能像error
函数中的字符串一样使用downloadFile()
,您应该使用这两个变量。 Golang是强类型的,无法更改变量的类型。您可以使用interfaces进行多态,但在这种情况下,您需要像这样一起返回err
和filename
:
package main
import (
"os"
"net/http"
"io"
"fmt"
"strings"
)
func downloadFile(url string) (err error, filename string) {
resp, err := http.Get(url)
defer resp.Body.Close()
if err != nil {
return
}
// extrage numele fisierului din linkul redirectionat.
finalURL := resp.Request.URL.String()
parts := strings.Split(finalURL, "/")
filename = parts[len(parts)-1]
out, err := os.Create(filename)
defer out.Close()
if err != nil {
return
}
_, err = io.Copy(out, resp.Body)
if err != nil {
return
}
return
}
func main() {
var url1 string = "https://transfer.sh/5e2iH/test.txt"
err, file := downloadFile(url1)
if err != nil {
panic(err.Error())
}
fmt.Println( file )
}