Lessons
Go Introduction
Go Get Started
Go Syntax
Go Comments
Go Variables
- Declare Variables
- Go में Variables का परिचय
- Go में Multiple Variable Declaration
- Variable Naming Rules (नामकरण के नियम)
Go Constants
Go Output
Go Data Types
- Basic Data Types
- Go Boolean Data Type (बूलियन डेटा प्रकार)
- Go Integer Data Types
- Go Float Data Types
- Go String Data Type
Go Arrays
Go Slices
Go Operators
- Go Operators
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
Go Conditions
Go Switch
Go Loops
Go Functions
Go Struct
Go Maps
Project Structure
Create Slice
Go Slices क्या हैं?
Slices, Arrays की तरह होते हैं, लेकिन अधिक शक्तिशाली और flexible होते हैं। Arrays की तरह, slices भी एक ही प्रकार के कई values को एक variable में store करते हैं। Arrays के विपरीत, slice की length runtime में बढ़ाई या घटाई जा सकती है।
Slice बनाने के तरीके
- Using []datatype{values}
- Create a slice from an array
- Using make() function
1. []datatype{values} से Slice बनाना
खाली slice बनाना:
myslice := []int{}
Initialized slice बनाना:
myslice := []int{1,2,3}
cap() function - slice की capacity बताता है।
package main
import "fmt"
func main() {
myslice1 := []int{}
fmt.Println(len(myslice1))
fmt.Println(cap(myslice1))
fmt.Println(myslice1)
myslice2 := []string{"Go", "Slices", "Are", "Powerful"}
fmt.Println(len(myslice2))
fmt.Println(cap(myslice2))
fmt.Println(myslice2)
}
2. Array से Slice बनाना
arr1 := [6]int{10,11,12,13,14,15}
myslice := arr1[2:4]
fmt.Printf("myslice = %v\n", myslice)
fmt.Printf("length = %d\n", len(myslice))
fmt.Printf("capacity = %d\n", cap(myslice))
Index 2 से शुरू, index 4 से पहले खत्म।
Capacity = array के end तक element की गिनती = 4
3. make() function से Slice बनाना
myslice1 := make([]int, 5, 10)
fmt.Printf("myslice1 = %v\n", myslice1)
fmt.Printf("length = %d\n", len(myslice1))
fmt.Printf("capacity = %d\n", cap(myslice1))
// capacity omitted
myslice2 := make([]int, 5)
fmt.Printf("myslice2 = %v\n", myslice2)
fmt.Printf("length = %d\n", len(myslice2))
fmt.Printf("capacity = %d\n", cap(myslice2))