英文:
Creating a new *Dialer with gomail.v2
问题
我正在使用gomail.v2
来发送电子邮件,我的代码运行良好。在组合了消息msg
之后,我可以直接运行以下代码:
import ("gopkg.in/gomail.v2")
...
d := gomail.NewDialer("smtp.example.com", 25, "username", "password")
return d.DialAndSend(msg)
}
当然,我想将其泛化为不特定的用户名和密码,并将其分离为自己的函数,所以我进行了桩代码:
import ("gopkg.in/gomail.v2")
...
d := MyDialer()
return d.DialAndSend(msg)
}
func MyDialer() *Dialer {
return gomail.NewDialer("smtp.example.com", 25, "username", "password")
}
但是,Go报错说它不知道Dialer
。
.\email.go:42: undefined: Dialer
为什么会这样?我使用的返回类型与NewDialer
相同,这不会引起任何问题。
func NewDialer(host string, port int, username, password string) *Dialer
我错过了什么?我运行了以下命令来确保我没有运行过时的软件包版本,但没有成功。
go get -u gopkg.in/gomail.v2
英文:
I'm using <a href="https://godoc.org/gopkg.in/gomail.v2">gomail.v2</a> to send emails, and my code works fine. After composing a message msg
I can just run
import ("gopkg.in/gomail.v2")
...
d := gomail.NewDialer("smtp.example.com", 25, "username", "password")
return d.DialAndSend(msg)
}
Of course I'd like to generalize this past a particular username and password and separate it into its own function, so I stubbed it out:
import ("gopkg.in/gomail.v2")
...
d := MyDialer()
return d.DialAndSend(msg)
}
func MyDialer() *Dialer {
return gomail.NewDialer("smtp.example.com", 25, "username", "password")
}
But go croaks, complaining that it doesn't know about Dialer.
> .\email.go:42: undefined: Dialer
Why is this? I'm using the same return type as NewDialer
, which doesn't cause any problems.
func NewDialer(host string, port int, username, password string) *Dialer
What am I missing? I ran
> go get -u gopkg.in/gomail.v2
to make sure I wasn't somehow running an out of date version of the package, but no luck there.
答案1
得分: 2
*Dialer
和*gomail.Dialer
是两种不同的类型。具体的错误是因为您的包中没有定义Dialer
类型,但您需要匹配签名中的类型,而不仅仅是名称。由于gomail.NewDialer
返回的是*gomail.Dialer
,所以可以使用以下方式:
func MyDialer() *gomail.Dialer {
英文:
*Dialer
and *gomail.Dialer
are 2 different types. The specific error is because you don't have a Dialer
type defined in your package, but you need to match the types in the signature, not just the name. Since gomail.NewDialer
returns a *gomail.Dialer
, use:
func MyDialer() *gomail.Dialer {
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论