go - 将类型变量传递给函数

标签 go type-conversion type-assertion

我试图通过将类型传递给函数来实现类型断言。换句话说,我正在尝试实现这样的目标:

// Note that this is pseudocode, because Type isn't the valid thing to use here
func myfunction(mystring string, mytype Type) {
    ...

    someInterface := translate(mystring)
    object, ok := someInterface.(mytype)

    ...  // Do other stuff
}

func main() {
    // What I want the function to be like
    myfunction("hello world", map[string]string)
}

为了在 myfunction 中成功执行类型断言,我需要在 myfunction 中使用什么正确的函数声明?

最佳答案

@hlin117,

嘿,如果我正确理解了你的问题并且你需要比较类型,你可以这样做:

package main

import (
    "fmt"
    "reflect"
)

func myfunction(v interface{}, mytype interface{}) bool {
    return reflect.TypeOf(v) == reflect.TypeOf(mytype)
}

func main() {

    assertNoMatch := myfunction("hello world", map[string]string{})

    fmt.Printf("%+v\n", assertNoMatch)

    assertMatch := myfunction("hello world", "stringSample")

    fmt.Printf("%+v\n", assertMatch)

}

方法是使用您想要匹配的类型的样本。

关于go - 将类型变量传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40895901/

相关文章:

go - 如何从 .kube/config 中设置的当前上下文获取命名空间

go - 使用反射获取指向值的指针

go - 如何在 golang 中记录类型断言错误?

c++ - 在 VC++ 中将 void 指针变量类型转换并分配给 Integer 变量。

string - 是否可以针对反引号键入断言?

go - 键入断言嵌套接口(interface)

sql - Golang、数据库/sql、Postgres - 在您需要结果时使用 QueryRow 和 INSERT 不良做法?

python - Go 中的字典

type-conversion - 转换容器类型?

PHP - 日期字符串转Mysql dateTime