golang 空結構體 struct{} 可以用來節省內存
a := struct{}{}
println(unsafe.Sizeof(a))
// Output: 0
理由如下:
- 如果使用的是map,而且map又很長,通常會節省不少資源
- 空struct{}也在向別人表明,這里并不需要一個值
本例說明在map里節省資源的用途:
set := make(map[string]struct{})
for _, value := range []string{"apple", "orange", "apple"} {
set[value] = struct{}{}
}
fmt.Println(set)
// Output: map[orange:{} apple:{}]
下例,演示了struct{}可以向人展示對象中不需要任何數據,僅包含需要方法。在調用也并無任何區別
type Lamp struct{}
func (l Lamp) On() {
println("On")
}
func (l Lamp) Off() {
println("Off")
}
func main() {
// Case #1.
var lamp Lamp
lamp.On()
lamp.Off()
// Output:
// on
// off
// Case #2.
Lamp{}.On()
Lamp{}.Off()
// Output:
// on
// off
}
還有其他情況,比如有時候使用channel,但并不需要附帶任何數據。
func worker(ch chan struct{}) {
// Receive a message from the main program.
-ch
println("roger")
// Send a message to the main program.
close(ch)
}
func main() {
ch := make(chan struct{})
go worker(ch)
// Send a message to a worker.
ch - struct{}{}
// Receive a message from the worker.
-ch
println(“roger")
// Output:
// roger
// roger
}
到此這篇關于Golang空結構體struct{}用途,你知道嗎的文章就介紹到這了,更多相關Golang空結構體struct{}內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- golang 如何用反射reflect操作結構體
- golang 實現兩個結構體復制字段
- golang通過反射設置結構體變量的值
- golang修改結構體中的切片值方法
- Golang自定義結構體轉map的操作
- golang 結構體初始化時賦值格式介紹
- 解決golang結構體tag編譯錯誤的問題