How to return a value from an if statement

package main

import "fmt"

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

}

playground_code

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.

1 Like

@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”));
}
}

1 Like

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

can you please share a code snippet with me?

thanks for your response… really appreciated

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.

2 Likes

actually, it’s really helpful. thanks

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