1 回答
TA贡献1818条经验 获得超7个赞
Golang 是一种强类型语言,这意味着函数的参数是已定义的并且不能不同。字符串是字符串并且只是字符串,结构是结构并且只是结构。接口是 golang 的说法“这可以是具有具有以下签名的方法的任何结构”。因此,您不能将 astring作为 a传递ProviderType,并且您的结构都没有实际实现您定义的接口方法,因此没有任何东西可以像您所布置的那样工作。要将您所掌握的内容重新组织成可能有效的内容:
const (
discordType = "discord"
slackType = "slack"
)
// This means this will match any struct that defines a method of
// SendNotification that takes no arguments and returns an error
type Notifier interface {
SendNotification() error
}
type SlackNotificationProvider struct {
WebHookURL string
}
// Adding this method means that it now matches the Notifier interface
func (s *SlackNotificationProvider) SendNotification() error {
// Do the work for slack here
}
type DiscordNotificationProvider struct {
WebHookURL string
}
// Adding this method means that it now matches the Notifier interface
func (s *DiscordNotificationProvider) SendNotification() error {
// Do the work for discord here
}
func NewNotifier(uri, typ string) Notifier {
switch typ {
case slackType:
return SlackNotificationProvider{
WebHookURL: uri,
}
case discordType:
return DiscordNotificationProvider{
WebHookURL: uri + "/slack",
}
}
return nil
}
// you'll need some way to figure out what type this is
// could be a parser or something, or you could just pass it
uri := config.Cfg.SlackWebHookURL
typ := getTypeOfWebhook(uri)
slackNotifier := NewNotifier(uri, typ)
就帮助解决此问题的文档而言,“Go By Examples”内容很好,我看到其他人已经链接了它。也就是说,具有一个方法的结构感觉应该是一个函数,您也可以将其定义为一种类型以允许您传回一些内容。例子:
type Foo func(string) string
func printer(f Foo, s string) {
fmt.Println(f(s))
}
func fnUpper(s string) string {
return strings.ToUpper(s)
}
func fnLower(s string) string {
return strings.ToLower(s)
}
func main() {
printer(fnUpper, "foo")
printer(fnLower, "BAR")
}
- 1 回答
- 0 关注
- 112 浏览
添加回答
举报