Home  >  Article  >  Backend Development  >  How can you perform Type Assertion in Go by passing in a type to a function?

How can you perform Type Assertion in Go by passing in a type to a function?

Susan Sarandon
Susan SarandonOriginal
2024-10-30 19:57:30575browse

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:

  • v is the variable holding the value you want to check.
  • mytype is a sample of the expected data type.

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!

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