1. 程式人生 > 程式設計 >Golang空結構體struct{}用途,你知道嗎

Golang空結構體struct{}用途,你知道嗎

golang 空結構體 struct{} 可以用來節省記憶體

a := struct{}{}
println(unsafe.Sizeof(a))
// Output: 0

理由如下:

  1. 如果使用的是map,而且map又很長,通常會節省不少資源
  2. 空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{}內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!