英文:
golang, use structs as argument into a function
问题
请问你需要关于这个问题的建议。我刚开始学习golang,已经遇到了这个问题。
例如:
package main
import (
"fmt"
)
type X struct{
x string
}
type Y struct{
y string
}
func main() {
var x []X
var y []Y
f(x)
f(y)
}
func f(value interface{}){
if v, ok := value.([]X); ok {
fmt.Println("this is X")
}
if v, ok := value.([]Y); ok {
fmt.Println("this is Y")
}
}
期望输出:this is X
this is Y
value interface{}
是错误的类型。我该如何将不同的结构体放入一个函数中,并动态定义其类型。是否有可能实现这样的功能?谢谢。
英文:
could you please advise on the question.
I just started to learn golang and have already choked with this situation.
For example:
package main
import (
"fmt"
)
type X struct{
x string
}
type Y struct{
y string
}
func main() {
var x []X
var y []Y
f(x)
f(y)
}
func f(value interface{}){
if(typeof(value) == "[]X"){
fmt.Println("this is X")
}
if(typeof(value) == "[]Y"){
fmt.Println("this is Y")
}
}
expected output: this is X
this is Y
value interface{}
is wrong type. How can I put different structures into one function and then dynamically define its type.
Is something like this possible?
Thanks.
答案1
得分: 4
你可以使用type switch来处理已知的确切类型。否则,你可以使用reflect包。
下面是使用类型切换方法的代码示例:
package main
import (
"fmt"
)
type X struct {
x string
}
type Y struct {
y string
}
func main() {
var x = []X{{"xx"}}
var y = []Y{{"yy"}}
f(x)
f(y)
}
func f(value interface{}) {
switch value := value.(type) {
case []X:
fmt.Println("这是 X", value)
case []Y:
fmt.Println("这是 Y", value)
default:
fmt.Println("这是 YoYo")
}
}
播放链接:这里
英文:
You may use a type switch if you know the exact possible types. Otherwise you may use the reflect package.
Here is code demonstrating the type switch approach:
package main
import (
"fmt"
)
type X struct {
x string
}
type Y struct {
y string
}
func main() {
var x = []X{{"xx"}}
var y = []Y{{"yy"}}
f(x)
f(y)
}
func f(value interface{}) {
switch value := value.(type) {
case []X:
fmt.Println("This is X", value)
case []Y:
fmt.Println("This is Y", value)
default:
fmt.Println("This is YoYo")
}
}
play link : here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论