如何从 if 语句中返回一个值到 Go 语言的函数中

huangapple go评论77阅读模式
英文:

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

问题

我在从Python转到Golang后遇到了一个问题。在Python中,如果在函数内部的if语句中声明了一个变量,那么该变量对于函数/方法来说是可见的,只要该语句在函数内部。

当我尝试在Golang中做类似的事情时,我无法在if语句之外使用该变量。

这个错误("Unresolved reference '...'")将在IDE中出现,并且代码将无法编译。

我的问题是,为什么会发生这种情况?

英文:

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).
如何从 if 语句中返回一个值到 Go 语言的函数中

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?
如何从 if 语句中返回一个值到 Go 语言的函数中

答案1

得分: -3

我在这个问题上遇到了困难,因为我没有意识到在 if 函数内部使用的变量对于函数来说是不可见的。

答案很简单 - 在这种情况下,你不需要返回值,只需要填充值即可。所以,在函数内部的 if 语句之前引入它,它将对函数和语句都可见。

// 用于演示的主要包
package main

import "fmt"

// sometype 组织数据流
type sometype struct {
    sometype1 string
}

// someaction 执行动作
func someaction(somedata sometype) {
    fmt.Printf("%v", somedata)
}

// somefunc 是一个函数
func somefunc(somedata int, somebool bool, anydata sometype) {
    // 引入变量
    var somenewdata sometype
    if somebool == true {
        // 用数据填充变量
        somenewdata = anydata
    }
    someaction(somenewdata)
}

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

希望对你有帮助!

英文:

I struggled with this problem as I didn't realise that it was implied that the variable which is used inside if-function is not visible for a function.

The answer is simple - you don't need to return the value in this case as you should just fill the value. So, you need to introduce it before the if-statement inside the function, and it will be visible for both: the function and the 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) {
	//introduce the variable
	var somenewdata sometype 
	if somebool == true {
		//fill the variable with data
		somenewdata = anydata
	}
	someaction(somenewdata)
}

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

}

huangapple
  • 本文由 发表于 2022年1月28日 19:21:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/70892898.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定