结构体的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| package main import "fmt"
type myint int
type Book struct{ title string auth string } func changeBook (book Book) { book.title = "三体" } func changeBook2 (book *Book) { book.title = "生死疲劳" } func main () { var a myint = 232 fmt.Println("a = ", a) fmt.Printf("type of a is %T\n", a) var book1 Book book1.title = "活着" book1.auth = "余华" fmt.Printf("%v\n", book1) changeBook(book1) fmt.Printf("%v\n", book1) changeBook2(&book1) fmt.Printf("%v\n", book1) }
|
检查结构体是否为空
在 Go 语言中,结构体不能为 nil,只有结构体指针可以为 nil。当你声明一个结构体变量时,它的字段会被初始化为零值。要检查结构体是否为空,你可以检查其所有字段是否为零值。对于结构体指针,你可以检查它是否为 nil。下面是如何检查空结构体和空指针的示例你可以参考一下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| mport "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.") } }
|