gpt4 book ai didi

go - 不可能型开关盒

转载 作者:IT老高 更新时间:2023-10-28 13:08:56 25 4
gpt4 key购买 nike

此程序无法编译:

package main

type Validator struct {
}

// Error implements error interface
func (v *Validator) Error() string {
return ""
}

func test() error {
return &Validator{}
}

func main() {
switch test().(type) {
case nil:
println("No error")
case Validator:
println("Validation error")
return
default:
println("Unknown error")
return
}
}

错误是:

prog.go:19: impossible type switch case: test() (type error) cannot have dynamic type Validator (missing Error method)

但是 Validator 结构体有方法 Error

最佳答案

你有两种不同的类型,Validator和指针类型*Validator,这两种类型有不同的方法集。

你只为指针定义了一个Error()方法,而Validator没有这个方法。

你可以做的是以下改变:

// Error implements error interface
func (v Validator) Error() string {
return ""
}

...

case *Validator, Validator: // You are actually getting a *Validator

这实现了 Validator*ValidatorError()。作为 Go specification 说:

The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T)

关于go - 不可能型开关盒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24593505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com