0

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:
    }
}

1 Answers1

0

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)

Para
  • 1,299
  • 4
  • 11