You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I've made 2 custom error types that implement error interface: customErr1 and customErr2. They both have a Message property.
The inspect(error) function checks for types using a typed switch statement and, if the error object is either of customErr or customErr2 type, accesses their Message property.
What I expected to see: typed switch statement compiled.
What I saw instead: compilation error:
prog.go:24: e.Message undefined (type error has no field or method Message)
The problematic line below is
case*customErr1, *customErr2:
What's weird is that the program works if the list is reduced to 1 item, i.e. one of the types is removed. However if the case list contains 2 items, the program doesn't compile and complains that "type error has no field or method Message". It's true that error doesn't implement Message, but that was the purpose of my type check in the first place.
The variable e in the typeswitch cannot have both type *customErr1 and customErr2. That's why it will have type error instead (same like in the default case). The solution is to use only one type per case clause where the e variable is used: http://play.golang.org/p/v7687VMgpR
Thanks for the quick reply. I'm still confused. The Go language spec suggests in its example that such construct is possible:
switchi:=x.(type) {
casebool, string:
printString("type is bool or string")
default:
printString("don't know the type")
}
Here we see the same case statement for both bool and string. Why wouldn't it be possible for two different types that implement the same interface, like in my example above?
In clauses with a case listing exactly one type, the variable has that type; otherwise, the variable has the type of the expression in the TypeSwitchGuard.
Let's move further discussion to the mailing list. This isn't a bug.
I've made 2 custom error types that implement
error
interface:customErr1
andcustomErr2
. They both have aMessage
property.The
inspect(error)
function checks for types using a typedswitch
statement and, if the error object is either ofcustomErr
orcustomErr2
type, accesses theirMessage
property.What I expected to see: typed
switch
statement compiled.What I saw instead: compilation error:
The problematic line below is
What's weird is that the program works if the list is reduced to 1 item, i.e. one of the types is removed. However if the
case
list contains 2 items, the program doesn't compile and complains that "type error has no field or method Message". It's true thaterror
doesn't implement Message, but that was the purpose of my type check in the first place.Full example on Go playground, inlined here:
go version go1.5.1 darwin/amd64
The text was updated successfully, but these errors were encountered: