'How to return a value from if-statement into a function golang

I had a problem when I started to use Golang after Python. In Python, a variable that is declared inside an if-statement will be visible for a function/method if the statement is inside the function.

from pydantic import BaseModel

class sometype(BaseModel):
    """
    A model describes new data structure which will be used
    """
    sometype1: str

def someaction(somedata:sometype):
    """
    do some action
    :param somedata: a sometype instance
    :return:
    """
    print("%s" % somedata.sometype1 )

def somefunc(somedata:int, somebool:bool, anydata:sometype):
    """
    It is a function
    :param somedata: some random int
    :param somebool: thing that should be True (else there will be an error)
    :param anydata: sometype instance
    :return:
    """
    if somebool==True:
        somenewdata=anydata
    someaction(somenewdata)

if __name__=="__main__":
    print("some")
    thedata :sometype = sometype(sometype1="stringtypedata")
    somefunc(1, True, thedata)

An IDE only can warn you ("Local variable '...' might be referenced before assignment") that this could not be referenced in some cases (to be precise - there will be no variable named "somenewdata" if the "somebool" be False). example of an IDE warning

When I tried to do something similar in Go - I couldn't use the variable outside if-statement.

// main package for demo
package main

import "fmt"

//sometype organizes dataflow
type sometype struct {
    sometype1 string
}

//someaction does action
func someaction(somedata sometype) {
    fmt.Printf("%v", somedata)
}

//somefunc is a function
func somefunc(somedata int, somebool bool, anydata sometype) {
    if somebool == true {
        somenewdata = anydata
    }
    someaction(somenewdata)
}

func main() {
    fmt.Println("some")
    thedata := sometype{"stringtype"}
    somefunc(1, true, thedata)

}

This error ("Unresolved reference "..."") will appear in IDE and the code will not compile. My question was - why does that happening? Golang error description



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source