How to return a value from an if statement


(Rana Umair) #1
package main

import "fmt"

func main() {
y := 3
if x := 2; x == y {
		return x
	} else {
		fmt.Println("Error")
	}

}

playground_code


(Christophe Meessen) #2

You are not allowed to return a value in a function that is defined to have no return value.

The return x is causing the compilation error.


(Shubh) #3

@rana It depends on how do you want to handle errors. if you want to stop program execution i suggest you to check [panic and recover].
Else you can use error interface which provides a good functionality for handling errors.

package main
import (
“fmt”
“errors”
)
func main(){
if …
else {
fmt.Println(errors.New(“This is a error”));
}
}


(Rana Umair) #4

Hi, how to then return a value from an if-statement?

can you please share a code snippet with me?


(Rana Umair) #5

thanks for your response… really appreciated


(Norbert Melzer) #6

By writing the if statement in a function that actually has a return type. main has none…

If you want to return an int, then you need to make your funtion return one:

func f() int {
  if 2 == 2 {
    return 4
  }
  return 0
}

Since you have a return type specified all branches of your function need to return a value of that type.


(Rana Umair) #7

actually, it’s really helpful. thanks