Go语言接口实现动态调用函数示例
import "fmt"
type A interface { aaa(ss string) }
type a struct{}
func (a *a) aaa(ss string) { fmt.Println('函数1' + ss) }
type b struct{}
func (b *b) aaa(ss string) { fmt.Println('函数2' + ss) }
func callAaa(name string, ss string) { var obj A if name == "a" { obj = &a{} } else if name == "b" { obj = &b{} } else { fmt.Println("无效的参数: ", name) return } obj.aaa(ss) }
// 调用方式: callAaa("a", "hello") callAaa("b", "world") callAaa("c", "oops") // 输出无效的参数: c
原文地址: https://www.cveoy.top/t/topic/lpOk 著作权归作者所有。请勿转载和采集!