golang

这个概念该如何理解呢?我们先看一段代码:

var w io.Writer // type-<nil>
w = new(bytes.Buffer) // type-*bytes.Buffer
w = nil // type-<nil>
wwfmt%T
fmt.Printf("%T\n",w)
io.Writernil==!=nil
w == nil // return true
ww*bytes.Buffer
package bytes

type Buffer struct {
    buf       []byte   // contents are the bytes buf[off : len(buf)]
    off       int      // read at &buf[off], write at &buf[len(buf)]
    bootstrap [64]byte // memory to hold first slice; helps small buffers avoid allocation.
    lastRead  readOp   // last read operation, so that Unread* can work correctly.
}
Writer
w.Write([]byte("ok"))
wWritePanicwnil

说到这里,大概能明白接口值的意义了,不过还有一个问题,那就是一个接口为空和一个接口包含空指针是否是一回事?我们来看一段代码:

func test(w io.Writer)  {

    if w != nil{
        w.Write([]byte("ok"))
    }
}

func main() {

    var buf *bytes.Buffer
    test(buf)
}
main()buf*bytes.Buffertest()w*bytes.Buffernilww != nil
var buf io.Writer // buf = new(bytes.Buffer)

我们再来看一段代码:

type Test interface {}

type Test1 interface {
    TestFunc()
}

type Structure struct {
    a int
}

func (s *Structure) TestFunc(){
    fmt.Println("Ok, Let's rock and roll!")
}

func fTest(t Test)  {
    fmt.Println(t == nil)
}

func fTest1(t1 Test1){
    fmt.Println(t1 == nil)
}

func fStructure(s *Structure){
    fmt.Println(s == nil)
}

func main() {
    var s *Structure = nil
    fTest(s) // false
    fTest1(s) // false
    fStructure(s) // true
    s.TestFunc() // Ok, Let's rock and roll!
}

执行一下代码,是否和预期的结果一样呢?Ok, Let's rock and roll!