golang,使用结构作为函数的参数

golang,使用结构作为函数的参数,go,Go,你能就这个问题提出建议吗。 我刚开始学咕噜,已经被这种情况噎住了 例如: 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) == "[

你能就这个问题提出建议吗。 我刚开始学咕噜,已经被这种情况噎住了

例如:

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
值接口{}
类型错误。如何将不同的结构放入一个函数中,然后动态定义其类型

这样的事情可能吗? 谢谢。

如果您知道确切的可能类型,您可以使用。否则,您可以使用该软件包

下面是演示类型切换方法的代码:

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")
    }
}
播放链接:

如果您知道确切的可能类型,可以使用。否则,您可以使用该软件包

下面是演示类型切换方法的代码:

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")
    }
}

播放链接:

您有一个同名的变量和函数。你想做什么?更新了。希望,现在很清楚了,您是在寻找类型断言还是类型开关?可能重复:您试图解决什么问题?您有一个变量和一个同名函数。你想做什么?更新了。希望,现在很清楚了,您是在寻找类型断言还是类型开关?可能重复:你想解决什么问题?