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 關注
- 165 瀏覽
添加回答
舉報