43

[golang] 为什么接口变量的值不是nil?

 3 years ago
source link: https://studygolang.com/articles/29132
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

测试代码

package main

import (
    "fmt"
)

func main() {
    doIt := func(args int) interface{} {
        var result *struct{} = nil
        if args > 0 {
            result = &struct{}{}
        }
        return result
    }

    if res := doIt(-1); res != nil {
        fmt.Println("res != nil")
    } else {
        fmt.Println("res == nil")
    }
}

上面的代码输出 res != nil

doIt的返回类型是 interface{} 空接口, 代码中 var result *struct{} = nil 是nil, 但是 返回的结果是 interface{} , 空接口

对于空接口, 空接口类型可以保存任何值,也可以从空接口中取出原值

接口类型本身是无法被值化的。在我们赋予它实际的值之前,它的值一定会是nil,这也是它的零值。 反过来讲,一旦它被赋予了某个实现类型的值,它的值就不再是nil了。

返回的空接口包含了指向对象result的类型信息(type)和数据指针(data)也就是说 接口变量的值并不等同于这个可被称为动态值(result)的副本。它会包含两个指针,一个指针指向动态值(result),一个指针指向类型信息

iface & eface

欢迎关注我们的微信公众号,每天学习Go知识

FveQFjN.jpg!web

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK