Multiple function types in mapping, Golang

WBOY
Release: 2024-02-12 08:39:09
forward
855 people have browsed it

Multiple function types in mapping, Golang

Map is a powerful data structure in Golang that allows us to associate one value with another value. In Golang, we can use mappings to implement various types of functions. PHP editor Youzi will introduce various function types in mapping in this article, including ordinary functions, anonymous functions and methods. Not only that, we'll explore how to use functions as values ​​in mappings and demonstrate their power and flexibility. Whether you are a beginner or an experienced Golang developer, this article will provide you with useful knowledge and examples to help you better understand and apply function types in mapping. Let’s start exploring!

Question content

I want to connect user input to a function. User input is a string. For example, "func_name=MyPrintf&s1=Hello, world\!" or "func_name=MyAdd&i1=1&i2=2"

The code of each function is,

func MyPrintf(s1 string) {
    fmt.Println(s1)
}

func MyAdd(i1, i2 int) {
    fmt.Println(i1, i2)
}
Copy after login

I want a map like below,

type Myfunc func(string) | func(int, int)   // <- Of course, it's wrong code, just I hope like this.

myMap := make(map[string]Myfunc)

myMap["MyPrintf"] = MyPrintf
myMap["MyAdd"] = MyAdd
Copy after login

myMap can call functions through the func_name string entered by the user.

myMap[func_name](s1) Output: Hello world! myMap[func_name](i1, i2) Output: 3

is it possible? Maybe I think using "eval" is possible, but I heard using "eval" is bad. So, I thought of using function pointers, but there are no function pointers in Golang.

I tried some Golang general programming,

type Myfunc interface {
    func(string) | func(int, int)
}

myMap := make(map[string]Myfunc)
Copy after login

Output: An error occurred: type Myfunc cannot be used outside a type constraint: interface contains a type constraint

Try again,

myMap := make(map[string]interface{})

myMap["MyPrintf"] = interface{}(MyPrintf)
myMap["MyPrintf"].(func(string))("Hello, world!")
Copy after login

Output: Hello, world!

myMap["MyAdd"] = interface{}(MyAdd)
myMap["MyAdd"].(func(int,int))(1, 2)
Copy after login

Output: 3

It works, but you have to specify the correct function type, which is not very comfortable. I think this way is not suitable for my scenario. Please give me help. I'm sorry for my poor English writing.

Solution

You can try this:

I must say this is not a good practice because the panic\error caused by the wrong type is not validated. I'll consider another approach.

package main

import "fmt"

type GeneralFunc func(args ...interface{})

func main() {
    // Create a map of functions with the type GeneralFunc
    functionsMap := map[string]GeneralFunc{
        "MyPrintf": func(args ...interface{}) { fmt.Println(args[0].(string)) },
        "MyAdd":    func(args ...interface{}) { fmt.Println(args[0].(int), args[1].(int)) },
    }

    // Use the functions from the map
    functionsMap["MyPrintf"]("Hello World")
    functionsMap["MyAdd"](2, 3)
}
Copy after login

The above is the detailed content of Multiple function types in mapping, Golang. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
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
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!