I have been declaring sentinel error types, as in https://play.golang.org/p/mhaBt3ehby0. However, it seems that the type assertion from any
ErrB always succeeds, even though
errA is an instance of
ErrA. I could understand this if I were using type aliases, but surely type
ErrA is distinct from type
I can fix the problem by doing https://play.golang.org/p/H14SERIJdem, but what is the explanation for the first scenario and is there a better way to do this than using
A non-constant value
x can be converted to type
T in any of these cases:
Explains the first example. But I can’t explain the second one which is based on composition.
error is an interface type
When you do a type assertion on an interface type, it just checks to see if it satisfies the given interface. That is, (in the example you gave) whether
errA satisfies the
errB interface. The value of
errA is not changed, but the resulting expression is of type
errB, and has methods from
errB. In this case both
errB are aliases for
error, so the type assertion really changes nothing. You’ve just succeeded in converting something of type
errA to type
Println() statements are printing two things that have the same value, so they print the same thing.
Right, thanks, its obvious when I think about it now.
ErrB genuinely is a new interface type, but it is an
interface type with the same layout as
error. I could equally well have defined
ErrB like https://play.golang.org/p/PavzI5z4PM5, and the type assertion works.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.