Home >Backend Development >Golang >How to Pass Type Variables to Functions for Type Assertions in Go?

How to Pass Type Variables to Functions for Type Assertions in Go?

DDD
DDDOriginal
2024-10-30 22:24:30283browse

How to Pass Type Variables to Functions for Type Assertions in Go?

Passing Type Variables to Functions for Type Assertions

You want to perform type assertions by passing a type into a function. Essentially, you aim to achieve the following:

<code class="go">// Note that this is pseudocode, because Type isn't valid here
func myfunction(mystring string, mytype Type) {
    ...

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

    ...  // Do other stuff
}

func main() {
    // Desired function call
    myfunction("hello world", map[string]string)
}</code>

To successfully perform type assertions in myfunction, use the following function declaration:

<code class="go">package main

import "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) // false

    assertMatch := myfunction("hello world", "stringSample")
    fmt.Printf("%+v\n", assertMatch) // true
}</code>

This approach involves using a sample of the type you want to match, ensuring that the types are identical for successful type assertion.

The above is the detailed content of How to Pass Type Variables to Functions for Type Assertions in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn