【发布时间】:2013-08-27 06:50:22
【问题描述】:
我正在使用go-flags 来解析命令行选项。
根据 go-flags 文档:
... [如果] 在命令行中指定了 -h 或 --help 参数,将自动打印帮助消息。此外, 返回特殊错误类型 ErrHelp。
我调用的方法是:
func (p *Parser) Parse() ([]string, error) {
我是这样称呼它的:
var opts struct {
// ...
}
func main() {
parser := flags.NewParser(&opts, flags.Default)
args, err := parser.Parse()
文件中定义 ErrHelp 的 sn-p 如下所示:
type ErrorType uint
const (
// Unknown or generic error
ErrUnknown ErrorType = iota
// Expected an argument but got none
ErrExpectedArgument
// ...
// The error contains the builtin help message
ErrHelp
// ...
)
// Error represents a parser error. The error returned from Parse is of this
// type. The error contains both a Type and Message.
type Error struct {
// The type of error
Type ErrorType
// The error message
Message string
}
// Get the errors error message.
func (e *Error) Error() string {
return e.Message
}
func newError(tp ErrorType, message string) *Error {
return &Error{
Type: tp,
Message: message,
}
}
所以他们有这个自定义的“错误”类型。在上面的 Parse() 方法中,在内部,错误是用这样的代码块创建的:
help.ShowHelp = func() error {
var b bytes.Buffer
p.WriteHelp(&b)
return newError(ErrHelp, b.String())
}
如您所见,newError() 返回“*Error”作为它的类型。但是上面的匿名函数返回类型“错误” - 所以这些类型必须兼容。(?)
但是现在回到最初的问题——我只是想看看我的“err”是否是一个“Error”并且成员“Type”是否等于 ErrHelp。所以我试试这个:
if err != nil && flags.Error(err).Type == flags.ErrHelp {
甚至只是这样:
fmt.Printf("test:", flags.Error(err))
无论哪种方式编译器都会给我:
main.go:37: cannot convert err (type error) to type flags.Error
但没有说明为什么不能进行转换。有什么想法吗?
(我不明白“*Error”是如何在上面的匿名函数中成功转换为“error”的,我更不明白为什么如果这样有效,那么我不能以另一种方式将其转换回来。 ..我一定错过了一些非常愚蠢的东西,但我没有看到它是什么。)
【问题讨论】: