将一个类型变量传递给函数。

huangapple go评论71阅读模式
英文:

Passing in a type variable into function

问题

我正在尝试通过将类型传递给函数来实现类型断言。换句话说,我想要实现类似于以下代码的功能:

// 注意,这只是伪代码,因为 Type 不是在这里使用的有效类型
func myfunction(mystring string, mytype Type) {
    ...
    
    someInterface := translate(mystring)
    object, ok := someInterface.(mytype)

    ...  // 做其他事情
}

func main() {
    // 我希望函数的使用方式
    myfunction("hello world", map[string]string)
}

myfunction 中,我需要使用什么样的函数声明才能成功执行类型断言?

英文:

I'm trying to achieve a type assertion by passing in a type into a function. In other words, I'm trying to achieve something like this:

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

What's the proper function declaration I need to use in myfunction, to successfully perform the type assertion in myfunction?

答案1

得分: 6

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

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)

}

这种方法是使用你想要匹配的类型的示例。

英文:

@hlin117,

Hey, if I understood your question correctly and you need to compare the types, here's what you can do:

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)

}

The approach is to use a sample of the type you'd like to match.

huangapple
  • 本文由 发表于 2016年12月1日 02:44:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/40895901.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定