0
0
Goprogramming~15 mins

Slice length and capacity in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Slice length and capacity
📖 Scenario: You are managing a list of fruits in a grocery store inventory system. You want to understand how slices work in Go, especially their length and capacity, to handle the inventory efficiently.
🎯 Goal: Learn how to create a slice, check its length and capacity, and understand how these properties change when slicing the slice.
📋 What You'll Learn
Create a slice of strings with exact fruits
Create a new slice from the original slice
Print the length and capacity of both slices
💡 Why This Matters
🌍 Real World
Slices are used in Go programs to manage collections of data efficiently, such as lists of items in inventory or user data.
💼 Career
Understanding slice length and capacity is essential for Go developers to write efficient and bug-free code when handling dynamic data.
Progress0 / 4 steps
1
Create the initial slice
Create a slice of strings called fruits with these exact values: "apple", "banana", "cherry", "date", "elderberry".
Go
Hint

Use []string{} to create a slice with the exact fruit names inside.

2
Create a new slice from the original
Create a new slice called citrus from fruits that contains only the elements from index 1 to 3 (inclusive start, exclusive end).
Go
Hint

Use slicing syntax fruits[1:4] to get elements from index 1 up to but not including 4.

3
Check length and capacity
Create two variables called fruitsLen and fruitsCap to store the length and capacity of fruits. Also create citrusLen and citrusCap for the length and capacity of citrus.
Go
Hint

Use len(slice) for length and cap(slice) for capacity.

4
Print the lengths and capacities
Print the length and capacity of fruits and citrus using fmt.Println with the exact format:
"fruits length: " followed by fruitsLen,
"fruits capacity: " followed by fruitsCap,
"citrus length: " followed by citrusLen,
"citrus capacity: " followed by citrusCap.
Go
Hint

Use fmt.Println four times with the exact text and variables.