douyao1994 2017-09-07 21:21 采纳率: 100%
浏览 23
已采纳

我可以通过相同的结果返回字符串或错误值吗?

i want execute function and return output results on variable, this is my actual code :

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 )

}

i want execute function downloadFile and return variable filename in variable filename2, return me this error, where im wrong ? im python developer, im sure to make stupid error :)

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
  • 写回答

2条回答 默认 最新

  • doupa8922 2017-09-07 21:35
    关注

    You can't use error like a string in the downloadFile() function, you should work with both variables. Golang is strongly typed and couldn't change the type of variable. You can use interfaces for polymorphism but in this case, you need just return err and filename together like this:

    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 )
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?