Wednesday, July 4, 2018

What it means to have an interface that has a dynamic type and dynamic value?


https://play.golang.org/p/1bT6HP54_fJ


Below code should explain when an interface seems nil but its not actually nil, because its dynamic type points to something concrete.


 ===== Code ====
package main

import (
"fmt"
"io"
"bytes"
)

func main() {
           // An interface which is nil.
var b io.Writer
fmt.Println(b==nil) // True

// An implementation of interface which is nil.
var bb *bytes.Buffer
fmt.Println(bb==nil) // True

// An interface whose dynamic type is concrete (*bytes.Buffer) and whose value is nil but holistically its not nil.
b = bb
fmt.Println(b==nil) // False and you would think its True
}


==== Output ====
true
true
false

No comments:

Post a Comment