"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Pass Type Variables to Functions for Type Assertions in Go?

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

Published on 2024-11-08
Browse:500

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:

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

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

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
}

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

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3