如何从函数返回动态值

如何实现这样的功能? ?<What_to_use_here>


func callfunc(type string) <What_to_use_here> {

    if type == "string"{

        return "I am a string"

     } else if type == "integer"{

       return 1

     }

    return nil

}


type Sample struct {

   value_int int

   value_str string

}


type Sample s

s.value_int = callFunc("integer")

s.value_str = callFunc("string")


我需要将来自调用Func的值分配给指定的类型,如下所示。所以我认为返回界面将不起作用。需要帮助。


吃鸡游戏
浏览 76回答 2
2回答

至尊宝的传说

type Sample struct {&nbsp; &nbsp; value_int int&nbsp; &nbsp; value_str string}func callFunc(typ string) interface{} {&nbsp; &nbsp; if typ == "string" {&nbsp; &nbsp; &nbsp; &nbsp; return "I am a string"&nbsp; &nbsp; } else if typ == "integer" {&nbsp; &nbsp; &nbsp; &nbsp; return 1&nbsp; &nbsp; }&nbsp; &nbsp; return nil}func main() {&nbsp; &nbsp; var s Sample&nbsp; &nbsp; s.value_int = callFunc("integer").(int)&nbsp; &nbsp; s.value_str = callFunc("string").(string)&nbsp; &nbsp; fmt.Println(s)}https://play.golang.org/p/QEPVMvAhkMQ

摇曳的蔷薇

你可以利用从go lang函数返回动态值,这里是一个简单的程序:interfacepackage mainimport (&nbsp; &nbsp; "fmt")func main() {&nbsp; &nbsp; data := callfunc("string")&nbsp; &nbsp; fmt.Println(data)&nbsp; &nbsp; data2 := callfunc("integer")&nbsp; &nbsp; fmt.Println(data2)}func callfunc(str string) interface{} {&nbsp; &nbsp; if str == "string" {&nbsp; &nbsp; &nbsp; &nbsp; return "I am a string"&nbsp; &nbsp; } else if str == "integer" {&nbsp; &nbsp; &nbsp; &nbsp; return 1&nbsp; &nbsp; }&nbsp; &nbsp; return nil}输出:I am a string1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go