如何从 if 语句返回值到 golang 函数中

问题描述 投票:0回答:1

我在使用Python之后开始使用Golang时遇到了问题。在 Python 中,如果语句位于函数内部,则在 if 语句内声明的变量对于函数/方法将是可见的。

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)

IDE 只能警告您(“局部变量 '...' 可能在赋值之前被引用”),在某些情况下无法引用该变量(准确地说 - 如果“somebool”,则不会有名为“somenewdata”的变量“是假的)。

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

// 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)

}

IDE 中将出现此错误(“未解析的引用“...””),并且代码将无法编译。 我的问题是 - 为什么会发生这种情况? 如果您遇到同样的问题,请投票。

python go difference
1个回答
-3
投票

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

答案很简单 - 在这种情况下您不需要返回值,因为您应该只填充该值。因此,您需要在函数内的 if 语句之前引入它,并且它对于函数和语句都可见。

如果答案解决了您的问题,请投票。

// 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)

}
© www.soinside.com 2019 - 2024. All rights reserved.