How to Perform Type Assertion with Function Parameters in Go?

Patricia Arquette
Release: 2024-11-02 00:18:02
Original
596 people have browsed it

How to Perform Type Assertion with Function Parameters in Go?

Type Assertion through Function Parameter

In an attempt to perform type assertion, you seek to pass a specific type into a function. Specifically, you aim to achieve a function declaration that enables you to assertively match against a provided type, as illustrated in the hypothetical function below:

// Note: Type isn't a valid type to use in Go
func myfunction(mystring string, mytype Type) {
    ...

    someInterface := translate(mystring)
    object, ok := someInterface.(mytype)

    ...  // Do other stuff
}
Copy after login

To successfully implement type assertion within myfunction, you should modify the function declaration to accept an interface{} parameter for mytype. Here's how you can achieve this:

func myfunction(v interface{}, mytype interface{}) bool {
    return reflect.TypeOf(v) == reflect.TypeOf(mytype)
}
Copy after login

This approach utilizes the reflect package to compare the type of the v parameter with the provided mytype interface. It returns a boolean value indicating whether the types match or not.

Here's an example that demonstrates how you can utilize this function:

package main

import (
    "fmt"
    "reflect"
)

func main() {

    assertNoMatch := myfunction("hello world", map[string]string{})

    fmt.Printf("%+v\n", assertNoMatch)

    assertMatch := myfunction("hello world", "stringSample")

    fmt.Printf("%+v\n", assertMatch)

}
Copy after login

In this example, the myfunction correctly determines whether the provided value matches the specified type and returns a boolean accordingly.

The above is the detailed content of How to Perform Type Assertion with Function Parameters in Go?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!