slice 瀹炵幇鍘熺悊鍙婁娇鐢ㄦ妧宸

鎴戜滑閮界煡閬揳rray鏄浐瀹氶暱搴︾殑鏁扮粍, slice鏄array鐨勬墿灞,鏈川涓婃槸鍩轰簬鏁扮粍瀹炵幇鐨

slice 缁撴瀯

slice涓 array 鏄竴涓寚閽堬紝瀹冩寚鍚戠殑鏄竴涓猘rray
len 浠h〃鐨勬槸杩欎釜slice涓殑鍏冪礌闀垮害
cap 鏄痵lice鐨勫閲
鍙傝 Golang slice 婧愮爜

    type slice struct {
        array unsafe.Pointer
        len   int
        cap   int
    }

澶嶅埗浠g爜
slice 鎵╁

s := []int{1,2,3,4,5,6}
s = append(s, 6)

濡傛灉鏂扮殑slice澶у皬鏄綋鍓嶅ぇ灏2鍊嶄互涓婏紝鍒欏ぇ灏忓闀夸负鏂板ぇ灏
濡傛灉褰撳墠slice cap 灏忎簬1024锛屾寜姣忔2鍊嶅闀匡紝鍚﹀垯姣忔鎸夊綋鍓嶅ぇ灏1/4澧為暱銆傜洿鍒板闀跨殑澶у皬瓒呰繃鎴栫瓑浜庢柊澶у皬
append鐨勫疄鐜版槸鍦ㄥ唴瀛樹腑灏唖lice鐨刟rray鍊艰祴鍊煎埌鏂扮敵璇风殑array涓
鎵╁婧愮爜瀹炵幇
鎬ц兘

閫氳繃涓婇潰鎴戜滑鐭ラ亾slice鐨勬墿瀹规秹鍙婂埌鍐呭瓨鐨勬嫹璐濓紝杩欐牱甯︽潵鐨勫ソ澶勬槸鏁版嵁瀛樺偍鍦ㄨ繛缁唴瀛樹笂锛屾瘮闅忔満璁块棶蹇緢澶氾紝鏈鐩存帴鐨勬ц兘鎻愬崌灏辨槸缂撳瓨鍛戒腑鐜囦細楂樺緢澶,杩欎篃灏辨槸涓轰粈涔坰lice涓嶉噰鐢ㄥ姩鎬侀摼琛ㄥ疄鐜扮殑鍘熷洜鍚
鎴戜滑鐭ラ亾鎷疯礉鍐呭瓨鏁版嵁鏄湁寮閿鐨勶紝 鑰屽叾涓渶澶х殑寮閿涓嶅湪 memmove 鏁版嵁涓婏紝鑰屾槸鍦ㄥ紑杈熶竴鍧楁柊鍐呭瓨malloc鍙婁箣鍚庣殑GC鍘嬪姏
鎷疯礉杩炵画鍐呭瓨鏄緢蹇殑锛岄殢鐫cap鍙樺ぇ锛屾嫹璐濇绘垚鏈繕鏄 O(N) ,鍙槸甯告暟澶т簡
鍋囧涓嶆兂鍙戠敓鎷疯礉锛岄偅浣犲氨娌℃湁杩炵画鍐呭瓨銆傛鏃堕殢鏈鸿闂紑閿浼氭槸锛氶摼琛 O(N), 2鍊嶅闀垮潡閾 O(LogN), 浜岀骇琛ㄤ竴涓父鏁板緢澶х殑 O(1)
褰撲綘鑳藉ぇ鑷寸煡閬撴墍闇鐨勬渶澶х┖闂达紙鍦ㄥぇ閮ㄥ垎鏃跺欓兘鏄殑锛夋椂锛屽湪make鐨勬椂鍊欓鐣欑浉搴旂殑 cap 灏卞ソ
濡傛灉闇瑕佺殑绌洪棿寰堝ぇ锛岃屼笖姣忔閮戒笉纭畾锛岄偅灏辫鍦ㄦ氮璐瑰唴瀛樺拰鑰 CPU 鍦 malloc + gc 涓婂仛鏉冭 
閾捐〃鐨勬煡鎵炬搷浣滄槸浠庣涓涓厓绱犲紑濮嬶紝鎵浠ョ浉瀵规暟缁勮鑰楁椂闂寸殑澶氾紝鍥犱负閲囩敤杩欐牱鐨勭粨鏋勫璇荤殑鎬ц兘鏈夊緢澶х殑鎻愰珮
閫夋嫨

slice鏄緢鐏垫椿鐨,澶ч儴鍒嗘儏鍐甸兘鑳借〃鐜扮殑寰堝ソ
浣嗕篃鏈夌壒娈婃儏鍐,slice鐨勫閲忚秴澶у苟涓旈渶瑕侀绻佺殑鏇存敼slice鐨勫唴瀹规椂,鏀圭敤list鏇村悎閫
娉ㄦ剰鐐

濡傛灉浣犵悊瑙d簡涓婇潰鍐呭锛岄偅涓嬮潰杩欐浠g爜鐨勮緭鍑虹粨鏋滀綘灏变笉鎰忓浜

s := []byte{1, 23, 4, 5, 67, 7}
s1 := s[2:3]
s1[0] = 100
fmt.Printf("s:%+v\n", s)
// s:[1 23 100 5 67 7]

娌¢敊锛屽垏鐗噑 绗笁浣嶇殑鍊4琚浛鎹负浜100,杩欐槸鍥犱负 鍒囩墖s1 鐨勫簳灞俛rray鎸囬拡鎸囧悜 鍒囩墖s 鐨勭涓変綅锛屽洜姝ゆ搷浣渟1浼氬奖鍝嶅垏鐗噑

All posts

Other pages


Deprecated: 鏂囦欢 娌℃湁 comments.php 鐨勪富棰 鑷増鏈 3.0.0 璧峰凡寮冪敤锛屼笖娌℃湁鍙敤鐨勬浛浠c 璇峰湪鎮ㄧ殑涓婚涓寘鍚竴涓 comments.php 妯℃澘銆 in /www/wwwroot/liguoqi.site/wp-includes/functions.php on line 6078

鍙戣〃鍥炲

鎮ㄧ殑鐢靛瓙閭鍦板潃涓嶄細琚叕寮銆 蹇呭~椤瑰凡鐢 * 鏍囨敞