Golang空結(jié)構(gòu)體struct{}用途,你知道嗎
golang 空結(jié)構(gòu)體 struct{} 可以用來節(jié)省內(nèi)存
a := struct{}{} println(unsafe.Sizeof(a)) // Output: 0
理由如下:
- 如果使用的是map,而且map又很長,通常會節(jié)省不少資源
- 空struct{}也在向別人表明,這里并不需要一個值
本例說明在map里節(jié)省資源的用途:
set := make(map[string]struct{}) for _, value := range []string{"apple", "orange", "apple"} { set[value] = struct{}{} } fmt.Println(set) // Output: map[orange:{} apple:{}]
下例,演示了struct{}可以向人展示對象中不需要任何數(shù)據(jù),僅包含需要方法。在調(diào)用也并無任何區(qū)別
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,但并不需要附帶任何數(shù)據(jù)。
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 }
到此這篇關(guān)于Golang空結(jié)構(gòu)體struct{}用途,你知道嗎的文章就介紹到這了,更多相關(guān)Golang空結(jié)構(gòu)體struct{}內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Golang+Vue輕松構(gòu)建Web應(yīng)用的方法步驟
本文主要介紹了Golang+Vue輕松構(gòu)建Web應(yīng)用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05淺談goland導(dǎo)入自定義包時出錯(一招解決問題)
這篇文章主要介紹了淺談goland導(dǎo)入自定義包時出錯(一招解決問題),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12Golang實現(xiàn)EasyCache緩存庫實例探究
這篇文章主要為大家介紹了Golang實現(xiàn)EasyCache緩存庫實例探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01Go語言使用defer+recover解決panic導(dǎo)致程序崩潰的問題
如果協(xié)程出現(xiàn)了panic,就會造成程序的崩潰,這時可以在goroutine中使用recover來捕獲panic,進行處理,本文就詳細的介紹一下,感興趣的可以了解一下2021-09-09