登录
首页 >  Golang >  Go问答

在 Go 语言中如何将 if 语句的值传递给函数函数

来源:stackoverflow

时间:2024-02-11 13:57:24 187浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《在 Go 语言中如何将 if 语句的值传递给函数函数》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

继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”为 false)。

当我尝试在 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 中,并且代码将无法编译。 我的问题是 - 为什么会发生这种情况? 如果您遇到同样的问题,请投票。


正确答案


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

答案很简单 - 在这种情况下您不需要返回值,因为您应该只填充该值。因此,您需要在函数内的 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)

}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>