Go Slices:
In Go, slices are more powerful, flexible, and convenient than arrays. A slice does not store any data, it just describes a section of an underlying array.
Declaring a Slice
You can create a slice using the built-in make function or by slicing an array:
go
package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4, 5}
fmt.Println("Slice:", numbers)
}Slicing an Array
You can create a slice from an array by specifying a range:
go
package main
import "fmt"
func main() {
arr := [5]int{10, 20, 30, 40, 50}
slice := arr[1:4]
fmt.Println("Sliced:", slice)
}Using make()
The make() function creates slices with a specified length and capacity:
go
package main
import "fmt"
func main() {
slice := make([]int, 3, 5)
fmt.Println("Slice:", slice)
fmt.Println("Length:", len(slice))
fmt.Println("Capacity:", cap(slice))
}Appending to a Slice
You can append elements to a slice using the built-in append() function:
go
package main
import "fmt"
func main() {
nums := []int{1, 2, 3}
nums = append(nums, 4, 5)
fmt.Println("After append:", nums)
}Copying a Slice
You can copy one slice to another using the built-in copy() function:
go
package main
import "fmt"
func main() {
src := []int{1, 2, 3}
dst := make([]int, len(src))
copy(dst, src)
fmt.Println("Copied slice:", dst)
}