Home > Article > Backend Development > How can you perform Type Assertion in Go by passing in a type to a function?
Type Assertion by Passing in Type to Function
In Go, type assertions involve verifying whether an interface value implements a specific type. To achieve this through a function, you can use the reflect package and provide a sample of the expected data type.
Function Declaration
The function declaration you should use is:
<code class="go">func myfunction(v interface{}, mytype interface{}) bool</code>
Where:
Usage
In the main function, you can call myfunction like this:
<code class="go">assertMatch := myfunction("hello world", "stringSample")</code>
Here, "stringSample" is a sample of the string type. If the v value is a string, the function will return true. Otherwise, it will return false.
Example
Here's an example:
<code class="go">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) }</code>
Output:
false true
The above is the detailed content of How can you perform Type Assertion in Go by passing in a type to a function?. For more information, please follow other related articles on the PHP Chinese website!