'Switch type behaving different for cases with multiple possibilities [duplicate]
Can anyone explain why the if statements behave differently in these two cases? It does not make sense to me.
package main
import (
"crypto/ecdsa"
"crypto/ed25519"
"fmt"
)
func main() {
var publicKey interface{}
publicKey = (ed25519.PublicKey)(nil)
switch k := publicKey.(type) {
case *ecdsa.PublicKey, ed25519.PublicKey:
if k == nil {
fmt.Println("It wont be printed")
}
default:
}
switch k := publicKey.(type) {
case ed25519.PublicKey:
if k == nil {
fmt.Println("It will be printed")
}
default:
}
}
Solution 1:[1]
publicKey is a interface{}, which has a type and value, both type and value is empty, it will be == nil;
publicKey.(type) is a interface{}, which has a type ed25519.PublicKey and a value nil
cases with multiple possibilities will change it type:
if i run:
case ed25519.PublicKey, *ecdsa.PublicKey:
publicKey.(type)
type: <interface{}|ed25519.PublicKey>
value: ked25519.PublicKey(nil)
publicKey.(type) == nil(because it has a type interface{})
if i run:
case ed25519.PublicKey:
publicKey.(type)
type: <ked25519.PublicKey>
value: ked25519.PublicKey(nil)
publicKey.(type) != nil(because it only has a type ked25519.PublicKey)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Para |
