golang 中的结构概念需要帮助

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


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(字符串类型)作为 NewNotifiergo 参数中的 ProviderType 类型 2. ProviderType.Slack 未定义(ProviderType 类型没有 Slack 方法)go


ibeautiful
浏览 77回答 1
1回答

qq_笑_17

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 errortype Notifier interface {    SendNotification() error}type SlackNotificationProvider struct {    WebHookURL string}// Adding this method means that it now matches the Notifier interfacefunc (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 interfacefunc (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 ituri := config.Cfg.SlackWebHookURLtyp := getTypeOfWebhook(uri)slackNotifier := NewNotifier(uri, typ)就帮助解决此问题的文档而言,“Go By Examples”内容很好,我看到其他人已经链接了它。也就是说,具有一个方法的结构感觉应该是一个函数,您也可以将其定义为一种类型以允许您传回一些内容。例子:type Foo func(string) stringfunc 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")}
打开App,查看更多内容
随时随地看视频慕课网APP