登录
首页 >  Golang >  Go问答

如何检查 Go 语言中的空结构体和空指针?

来源:SegmentFault

时间:2023-04-25 22:08:27 147浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《如何检查 Go 语言中的空结构体和空指针?》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

题目描述

如何检查 Go 语言中的空结构体和空指针?

题目来源及自己的思路

最近在检查产品是否为空,看一下如下代码:

package main

import "fmt"

type Product struct {
    name, category string
    price          float64
    upc            int64
}

func main() {

    var prd Product
    var prdPtr *Product

    fmt.Println("Value: ", prd.name, prd.category, prd.price)

    fmt.Println("Pointer: ", prdPtr)
}

这样直接运行可以得到 Go 为我们生成的空类型,打印结果如下:

正确答案

在 Go 语言中,结构体不能为 nil,只有结构体指针可以为 nil。当你声明一个结构体变量时,它的字段会被初始化为零值。要检查结构体是否为空,你可以检查其所有字段是否为零值。对于结构体指针,你可以检查它是否为 nil。下面是如何检查空结构体和空指针的示例你可以参考一下:

import "fmt" type Product struct { name, category string price float64 upc int64 } func isProductEmpty(prd Product) bool { return prd.name == "" && prd.category == "" && prd.price == 0 && prd.upc == 0 } func main() { var prd Product var prdPtr *Product fmt.Println("Value: ", prd.name, prd.category, prd.price) fmt.Println("Pointer: ", prdPtr) // 检查结构体是否为空 if isProductEmpty(prd) { fmt.Println("The product struct is empty.") } else { fmt.Println("The product struct is not empty.") } // 检查结构体指针是否为空 if prdPtr == nil { fmt.Println("The product pointer is nil.") } else { fmt.Println("The product pointer is not nil.") } }

以上就是《如何检查 Go 语言中的空结构体和空指针?》的详细内容,更多关于mysql的资料请关注golang学习网公众号!

声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>