首页 > 解决方案 > golang中结构概念需要帮助

问题描述

我想在 NewNotifier 函数中使用 slacknotificationprovider。我该怎么做。我还想在 newNotifier 函数中发送一个字符串(config.Cfg.SlackWebHookURL)。我应该怎么办?另外请建议我一些材料来更深入地了解 golang 中的结构和接口。我还想知道为什么 ProviderType.Slack 没有像我在 ProviderType 结构中提到的那样定义为 SlackNotificationProvider 类型?谢谢。

type SlackNotificationProvider struct {
    SlackWebHookURL string
    PostPayload     PostPayload
}
type ProviderType struct {
    Slack   SlackNotificationProvider
    Discord DiscordNotificationProvider
}
type Notifier interface {
    SendNotification() error
}
func NewNotifier(providerType ProviderType) Notifier {
    if providerType == ProviderType.Slack {
        return SlackNotificationProvider{
            SlackWebHookURL: SlackWebHookURL,
        }
    } else if providerType == ProviderType.Discord {
        return DiscordNotificationProvider{
            DiscordWebHookURL: SlackWebHookURL + "/slack",
        }
    }
    return nil
}
slackNotifier := NewNotifier(config.Cfg.SlackWebHookURL)

错误: 1. 无法使用 config.Cfg.SlackWebHookURL (type string) 作为 NewNotifiergo 参数中的 ProviderType 类型 2. ProviderType.Slack 未定义(类型 ProviderType 没有方法 Slack)go

标签: go

解决方案


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 Example”的东西很好,我看到其他人已经把它联系起来了。也就是说,具有一种方法的结构感觉应该是一个函数,您也可以将其定义为一种类型以允许您传回一些东西。例子:

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")
}

推荐阅读