您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“golang中set數(shù)據(jù)結(jié)構(gòu)如何使用”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“golang中set數(shù)據(jù)結(jié)構(gòu)如何使用”吧!
golang中沒有set數(shù)據(jù)結(jié)構(gòu),一般是通過map實現(xiàn),因為map的key值是不能重復(fù)的
示例
type empty struct { } // golang中的set數(shù)據(jù)類型 func MakeGolangSet(){ // 首先,空結(jié)構(gòu)體內(nèi)存消耗為0,其它數(shù)據(jù)結(jié)構(gòu)如布爾值等均存在內(nèi)存消耗 var e empty fmt.Printf("empty struct memory is %v\n", unsafe.Sizeof(e)) fmt.Printf("bool memory is %v\n", unsafe.Sizeof(false)) set := make(map[string]struct{}) // ADD set["foo"] = e // DELETE delete(set, "foo") // set的規(guī)模 size := len(set) fmt.Printf("set size is %v\n", size) // 判斷是否存在 set["foo"] = e value, exist := set["foo"] fmt.Printf("value is %v\n, exist is %v\n", value, exist) }
找兩個數(shù)組的交集
// 兩個數(shù)組的交集 func SectionWithTwoArray(num1, num2 []int) []int{ set := make(map[int]struct{}, 0) var res []int for _, v := range num1 { if _, ok := set[v]; !ok { // 去重 set[v] = struct{}{} } } for _, v := range num2 { if _, ok := set[v]; ok { res = append(res, v) // 將此v刪掉,避免結(jié)果中出現(xiàn)重復(fù)數(shù)據(jù) delete(set, v) } } return res }
到此,相信大家對“golang中set數(shù)據(jù)結(jié)構(gòu)如何使用”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。