Golang中 struct{} 和 struct{}{}區別


struct是Go中的關鍵字,用於定義結構類型。
例如:

type User struct {
    Name string
    Age  int
}

struct {} :表示struct類型

struct {}是一個無元素的結構體類型,通常在沒有信息存儲時使用。優點是大小為0,不需要內存來存儲struct {}類型的值。

struct {} {}:表示struct類型的值,該值也是空。

struct {} {}是一個復合字面量,它構造了一個struct {}類型的值,該值也是空。

例子

var set map[string]struct{}
// Initialize the set
set = make(map[string]struct{})

// Add some values to the set:
set["red"] = struct{}{}
set["blue"] = struct{}{}

// Check if a value is in the map:
_, ok := set["red"]
fmt.Println("Is red in the map?", ok)
_, ok = set["green"]
fmt.Println("Is green in the map?", ok)

輸出內容

Is red in the map? true
Is green in the map? false


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM