1 回答

TA貢獻1818條經(jīng)驗 獲得超7個贊
Golang 是一種強類型語言,這意味著函數(shù)的參數(shù)是已定義的并且不能不同。字符串是字符串并且只是字符串,結(jié)構(gòu)是結(jié)構(gòu)并且只是結(jié)構(gòu)。接口是 golang 的說法“這可以是具有具有以下簽名的方法的任何結(jié)構(gòu)”。因此,您不能將 astring作為 a傳遞ProviderType,并且您的結(jié)構(gòu)都沒有實際實現(xiàn)您定義的接口方法,因此沒有任何東西可以像您所布置的那樣工作。要將您所掌握的內(nèi)容重新組織成可能有效的內(nèi)容:
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”內(nèi)容很好,我看到其他人已經(jīng)鏈接了它。也就是說,具有一個方法的結(jié)構(gòu)感覺應(yīng)該是一個函數(shù),您也可以將其定義為一種類型以允許您傳回一些內(nèi)容。例子:
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 關(guān)注
- 147 瀏覽
添加回答
舉報