Return .\test.go:25:1: missing return at end of function why?

here my code

    package main

import (
   "fmt"
   "io/ioutil"
   "net/http"
    "os"
)

func getbalance(address string) string {
  response, err := http.Get("https://blockchain.info/q/addressbalance/" + address)
  if err != nil {
      fmt.Printf("%s", err)
      os.Exit(1)
  } else {
      defer response.Body.Close()
      contents, err := ioutil.ReadAll(response.Body)
      if err != nil {
          fmt.Printf("%s", err)
          os.Exit(1)
      }
      fmt.Printf("%s\n", string(contents))
      return string(contents)
  }
}


func main() {
  finalB := getbalance("1A63imbiQBtsnTqtUpuUT5WL2Ti7oKNLeg")
  fmt.Printf("Final Balance: %s", finalB)
}

return .\test.go:25:1: missing return at end of function
why ?

getbalance is missing a final return statement.

Currently the compiler thinks, that in case of err != nil you do not return anything, as it con not see through os.Exit().

A more sane solution would probably be to not have the else branch, but keep it “inline”:

func getbalance(address string) string {
  response, err := http.Get("https://blockchain.info/q/addressbalance/" + address)
  if err != nil {
      fmt.Printf("%s", err)
      os.Exit(1)
  }
  defer response.Body.Close()
  contents, err := ioutil.ReadAll(response.Body)
  if err != nil {
    fmt.Printf("%s", err)
    os.Exit(1)
  }
  fmt.Printf("%s\n", string(contents))
  return string(contents)
}

thank you very much i see your code for anderstand

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.