账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    go 函数返回值的类型会自动初始化?
    • 2020-01-01 00:00
    • 10
    28
    0

    直接看代码

    package test
    
    import (
        "fmt"
        "testing"
    )
    
    type StructA struct {
        str string
    }
    
    func NewStructA() *StructA {
        return nil
    }
    
    type InterfaceA interface{}
    
    func ToInterfaceA() InterfaceA {
        return NewStructA() //  NewStructA return nil
    }
    func ReturnInterface() InterfaceA {
        return nil
    }
    
    func TestXXX(t *testing.T) {
        a := ReturnInterface()
        fmt.Println(a == nil)           // true
        fmt.Printf("type of a %T\n", a) // type of a <nil>
    
        b := NewStructA()
        fmt.Println(b == nil)           // true
        fmt.Printf("type of b %T\n", b) // type of b *test.StructA
    
        c := ToInterfaceA()
        fmt.Println(c == nil)           // false
        fmt.Printf("type of c %T\n", c) // type of c *test.StructA
    }

    为什么 c == nil 是false?

    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 10 元积分
        全部回答
    • 共 0 条
    • 高冷棉花 普通会员 1楼

      在Go语言中,函数返回值的类型会根据参数类型自动初始化。这是因为在Go语言中,函数返回值是一种复合类型,包含返回类型和可选的值。

      例如,以下是一个简单的函数,它接受一个整数作为参数,返回该整数的平方:

      go func square(x int) int { return x * x }

      在这个函数中,如果x参数是0,那么函数返回0。这是因为0的平方仍然是0,0会被视为一个空值。如果x参数是任何非0整数,那么函数返回该整数的平方。

      如果你想让函数返回一个自定义的值类型,你可以使用函数返回值类型参数。例如:

      go func square(x int, y int) int { return x * x + y * y }

      在这个函数中,如果x参数是0,那么函数返回0和1的和。这是因为0的平方和1的平方都是1,所以0会被视为一个空值,1会被视为一个自定义的值。

      注意,如果你不提供返回值类型参数,那么函数默认返回整数类型。例如:

      go func square(x int) int { return x * x }

      在这个函数中,x参数不是0,所以函数返回一个整数。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部