golang how can I use struct name as map key

huangapple go评论65阅读模式
英文:

golang how can I use struct name as map key

问题

你可以使用反射(reflection)来构建这个映射(map)。以下是一个示例代码:

package main

import (
	"fmt"
	"reflect"
)

type A struct {
	a1 int
	a2 string
}

type B struct {
	b1 int
	b2 string
}

type C struct {
	c1 int
	c2 string
}

func processA(arg interface{}) {
	fmt.Println("Processing A:", arg.(A))
}

func processB(arg interface{}) {
	fmt.Println("Processing B:", arg.(B))
}

func processC(arg interface{}) {
	fmt.Println("Processing C:", arg.(C))
}

func main() {
	funcMap := make(map[reflect.Type]func(interface{}))
	funcMap[reflect.TypeOf(A{})] = processA
	funcMap[reflect.TypeOf(B{})] = processB
	funcMap[reflect.TypeOf(C{})] = processC

	arg := A{a1: 1, a2: "Hello"}

	for k, v := range funcMap {
		if k == reflect.TypeOf(arg) {
			v(arg)
		}
	}
}

在这个示例中,我们首先定义了结构体A、B和C,然后定义了对应的处理函数processA、processB和processC。接下来,我们创建了一个空的映射funcMap,键的类型为reflect.Type,值的类型为func(interface{})。然后,我们将结构体类型和对应的处理函数添加到映射中。最后,我们定义了一个输入参数arg,并使用反射来判断arg的类型,并根据类型在映射中找到对应的处理函数进行处理。

希望这可以帮助到你!如果有任何其他问题,请随时问我。

英文:
type A struct {
	a1 int
	a2 string
}
type B struct {
	b1 int
	b2 string
}
type C struct {
	c1 int
	c2 string
}

there are 3 structs, I want put the names into a map as key, and process func as map value

(instead of type-switch)

input arg is a interface, use for loop to judge what struct this interface is. And process this arg by process func in map value.
about:

var funcMap map[structName]func(arg){A:processA, B:processB, C:processC}

func testFunc(arg) {
    for k, v in range funcMap {
        if k == reflect.TypeOf(arg) {
            v(arg)
        }
    }
} 

how can I build this map??? hope code, thanks! (^o^)

答案1

得分: 3

你想要在reflect.Type上索引你的映射:

type funcMapType map[reflect.Type]func(interface{})

var funcMap funcMapType

然后注册一个类型和一个函数:

funcMap[reflect.TypeOf(A{})] = func(v interface{}) { log.Println("found A") }

如果你的函数需要修改结构体,你需要注册结构体类型的指针:

funcMap[reflect.TypeOf(&A{})] = func(v interface{}) { log.Println("found *A") }

链接:https://play.golang.org/p/LKramgSc_gz

英文:

You want to index your map on reflect.Type:

type funcMapType map[reflect.Type]func(interface{})

var funcMap funcMapType

then to register a type with a function:

funcMap[reflect.TypeOf(A{})] = func(v interface{}) { log.Println("found A") }

if your function needs to modify the struct, you'll need to register a pointer to the struct type:

funcMap[reflect.TypeOf(&A{})] = func(v interface{}) { log.Println("found *A") }

https://play.golang.org/p/LKramgSc_gz

huangapple
  • 本文由 发表于 2021年9月16日 20:46:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/69208715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定