Go Slices এর Capacity বুঝতে হলে

A highly motivated and experienced full-stack developer with a proven track record of developing and deploying web applications. Skilled in a range of programming languages and frameworks, as well as database technologies. Comfortable working in a fast-paced environment and able to adapt to new technologies quickly. A team player who is also able to work independently when required.
Go programming language এ slice একটি fundamental data structure। প্রোগ্রামিং এর শুরুতেই অনেকের কাছে slice এর length আর capacity নিয়ে confusion থাকে। আজকে আমরা এই concept টা clear করব একটি simple example দিয়ে।
Slice এর Capacity কি?
Slice হল Go তে array এর flexible version। Slice এর দুইটা important property আছে:
Length: slice এ কয়টা element আছে
Capacity: slice যতগুলো element ধারণ করতে পারে underlying array তে
Capacity Calculate করার Formula
যখন আমরা original[i:j] এভাবে slice করি, তখন capacity হয়:
Capacity = cap(original) - i
এখানে i হল starting index। এই formula টা মনে রাখলেই slice নিয়ে কাজ করা অনেক সহজ হয়ে যাবে!
একটি Example দিয়ে বুঝি
আসুন একটি simple code দেখি:
base := make([]int, 4, 8) // len=4, cap=8 [0, 0, 0, 0] [0, 0, 0, 0]
a := base[1:3] // [0, 0], len = 2, cap = 7
b := append(a, 9, 9, 9) // [0, 0, 9 ,9 ,9] len = 5, cap = 7
fmt.Println(len(a), cap(a)) // len = 2, cap = 7
fmt.Println(len(b), cap(b)) // len = 5, cap = 7
এখানে কি হচ্ছে:
baseslice create করলামmakeদিয়ে:Length: 4 (শুরুতে 4টা element, সবগুলো 0)
Capacity: 8 (সর্বোচ্চ 8টা element রাখতে পারবে)
aহলbaseথেকে একটি sub-slice:base[1:3]মানে index 1 থেকে শুরু করে 3 পর্যন্ত (কিন্তু 3 included নয়)Length = 3 - 1 = 2
Capacity = cap(base) - 1 = 8 - 1 = 7
bslice টাaথেকে append করে বানানো:aএর 2টা element এর সাথে আরও 3টা element (9, 9, 9) add করলামLength = 2 + 3 = 5
Capacity = 7 (যেহেতু
aএর capacity ছিল 7 আর new length 5, তাই capacity বাড়ানোর দরকার পড়েনি)
Visual Representation
base: [0, 0, 0, 0, _, _, _, _] // len=4, cap=8
0 1 2 3 4 5 6 7 // indices
a: [0, 0] // len=2, cap=7
1 2 // indices from base
b: [0, 0, 9, 9, 9] // len=5, cap=7
1 2 3 4 5 // indices from base
Interview Questions জন্য Tips
Interview তে slice capacity সম্পর্কে প্রশ্ন করা হলে:
original[i:j]এর capacity =cap(original) - iformula টা মনে রাখুনappendoperation এর পরে capacity বাড়ে শুধুমাত্র যখন new elements add করার পর slice এর size বর্তমান capacity কে cross করেmake([]type, length, capacity)দিয়ে নতুন slice বানানোর সময় direct capacity set করা যায়
Summary
Go slice এর capacity নিয়ে confusion থাকলে এই formula টা মনে রাখুন:
original[i:j]slice এর capacity =cap(original) - i
এটা বুঝতে পারলে, slice নিয়ে কাজ করা অনেক সহজ হয়ে যাবে, এবং memory performance ভালো করতে সাহায্য করবে।



