Home > Backend Development > Golang > 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
Release: 2024-10-30 19:57:30
Original
665 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

Output:

false
true
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template