我在想什麼「struct {}」和「struct {} {}」在Go中有什麼意思?一個例子如下:struct {}和struct {} {}如何在Go中工作?
array[index] = struct{}{}
或
make(map[type]struct{})
我在想什麼「struct {}」和「struct {} {}」在Go中有什麼意思?一個例子如下:struct {}和struct {} {}如何在Go中工作?
array[index] = struct{}{}
或
make(map[type]struct{})
struct
在Go一個keyword。它用於定義struct types,它是一系列命名元素。
例如:
type Person struct {
Name string
Age int
}
struct{}
的是struct
類型具有零個元素。當不存儲信息時經常使用它。它具有0大小的好處,所以通常不需要存儲器來存儲struct{}
類型的值。
struct{}{}
另一方面是composite literal,它構造了一個值爲struct{}
的值。複合文字爲結構,數組,地圖和切片等類型構造值。它的語法是大括號中的元素後面的類型。由於「空」結構(struct{}
)無域,元素列表也爲空:
struct{} {}
|^ |^
type empty element list
舉個例子,讓我們創建一個圍棋「設置」。 Go沒有內置的數據結構,但它有一個內置映射。我們可以使用地圖作爲一個集合,因爲地圖最多隻能有一個給定鍵的條目。由於我們只想將鍵(元素)存儲在地圖中,因此我們可以選擇地圖值類型爲struct{}
。
與string
元件A圖:
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)
輸出(嘗試在Go Playground):
Is red in the map? true
Is green in the map? false
注意,然而,它可以是在創建時使用bool
作爲值類型更方便作爲檢查元素是否在其中的語法的映射集更簡單。有關詳細信息,請參閱How can I create an array that contains unique strings?。
正如指出的izca:
結構是用於定義結構類型的是你決定的任何任意類型的變量組成的只是用戶定義類型一展身手的關鍵字。
type Person struct {
Name string
Age int
}
結構體也可以用零元素清空。 但是Struct {} {}具有不同的含義。這是一個複合結構文字。它內聯定義了一個結構類型並定義了一個結構並且不分配任何屬性。
emptyStruct := Struct{} // This is an illegal operation
// you define an inline struct literal with no types
// the same is true for the following
car := struct{
Speed int
Weight float
}
// you define a struct be do now create an instance and assign it to car
// the following however is completely valid
car2 := struct{
Speed int
Weight float
}{6, 7.1}
//car2 now has a Speed of 6 and Weight of 7.1
這裏此行僅僅是創建一個地圖是結構文本這是完全合法的。
make(map[type]struct{})
它是相同
make(map[type]struct{
x int
y int
})