Skip to content

Instantly share code, notes, and snippets.

@cored
Created November 20, 2024 22:21
Show Gist options
  • Save cored/7d909dc915284dd80843922230f7af64 to your computer and use it in GitHub Desktop.
Save cored/7d909dc915284dd80843922230f7af64 to your computer and use it in GitHub Desktop.
package main
import "fmt"
func main() {
// Initialize an array
arr := [5]int{10, 20, 30, 40, 50}
// Create a slice from the array
slice := arr[1:4] // Slice starting at index 1 (inclusive) and ending at index 4 (exclusive)
// Print the original slice
fmt.Println("Original Slice:", slice)
// Accessing and modifying elements in the slice
fmt.Println("Element at index 0:", slice[0]) // Should print 20
slice[0] = 99 // Modify the first element in the slice
fmt.Println("Modified Slice:", slice) // Should print [99 30 40]
// Create a new slice from the original slice by specifying a different range
newSlice := slice[1:] // Slice from index 1 (inclusive) to the end
fmt.Println("New Slice:", newSlice) // Should print [30 40]
// You can also create a slice without a start index, defaulting to 0
anotherSlice := arr[:3] // Slice starting from index 0 up to index 3 (exclusive)
fmt.Println("Another Slice:", anotherSlice) // Should print [10 20 30]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment