Home >Backend Development >Golang >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!