英文:
How to return dynamic values from a function
问题
如何实现这样的函数?<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
}
var s Sample
s.value_int = callFunc("integer")
s.value_str = callFunc("string")
我需要将来自callFunc的值分配给指定的类型,如示例所示。所以我认为返回interface类型不起作用。需要帮助。
英文:
How to implement a function like this? <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")
I need to assign the value coming from the callFunc to a specified type as shown. So I think returning interface will not work. Need help.
答案1
得分: 1
type Sample struct {
value_int int
value_str string
}
func callFunc(typ string) interface{} {
if typ == "string" {
return "我是一个字符串"
} else if typ == "integer" {
return 1
}
return nil
}
func main() {
var s Sample
s.value_int = callFunc("integer").(int)
s.value_str = callFunc("string").(string)
fmt.Println(s)
}
https://play.golang.org/p/QEPVMvAhkMQ
英文:
type Sample struct {
value_int int
value_str string
}
func callFunc(typ string) interface{} {
if typ == "string" {
return "I am a string"
} else if typ == "integer" {
return 1
}
return nil
}
func main() {
var s Sample
s.value_int = callFunc("integer").(int)
s.value_str = callFunc("string").(string)
fmt.Println(s)
}
答案2
得分: 1
你可以使用interface
来从Go语言函数中返回动态值,以下是一个简单的示例程序:
package main
import (
"fmt"
)
func main() {
data := callfunc("string")
fmt.Println(data)
data2 := callfunc("integer")
fmt.Println(data2)
}
func callfunc(str string) interface{} {
if str == "string" {
return "I am a string"
} else if str == "integer" {
return 1
}
return nil
}
输出结果:
I am a string
1
英文:
You can make use of interface
to return dynamic values from go lang function,here is simple program for the same:
package main
import (
"fmt"
)
func main() {
data := callfunc("string")
fmt.Println(data)
data2 := callfunc("integer")
fmt.Println(data2)
}
func callfunc(str string) interface{} {
if str == "string" {
return "I am a string"
} else if str == "integer" {
return 1
}
return nil
}
Output:
I am a string
1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论