Slice Length vs Capacity
Part of the Fundamentals section of Coddy's GO journey — lesson 77 of 109.
In Go, length and capacity are two different properties of slices.
Create a slice with make:
numbers := make([]int, 3, 5)
fmt.Println("Length:", len(numbers))
fmt.Println("Capacity:", cap(numbers))This displays:
Length: 3
Capacity: 5Length is the number of elements currently in the slice. Capacity is the maximum number of elements the slice can hold before needing to grow.
Challenge
Beginnerlen() and cap() functions. The len() function returns the current number of elements in a slice, while cap() returns the capacity (maximum number of elements before reallocation is needed).Your task is to complete the code to print both the length and capacity of the given slice.
Cheat sheet
In Go, slices have two properties: length and capacity.
Length is the number of elements currently in the slice. Capacity is the maximum number of elements the slice can hold before needing to grow.
Use len() to get the length and cap() to get the capacity:
numbers := make([]int, 3, 5)
fmt.Println("Length:", len(numbers)) // Length: 3
fmt.Println("Capacity:", cap(numbers)) // Capacity: 5Try it yourself
package main
import "fmt"
func main() {
// A slice with 3 elements but capacity of 5
numbers := make([]int, 3, 5)
// TODO: Print the length of the slice using len()
fmt.Println("Length:", ?)
// TODO: Print the capacity of the slice using cap()
fmt.Println("Capacity:", ?)
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison Operators - Part 1Comparison Operators - Part 2Logical AND OperatorLogical OR OperatorLogical NOT OperatorOperator Precedence BasicsRecap - Making Comparisons7Control Flow: Loops
What The `for` Loop ExplainedFor Loop - BasicFor Loop - Condition OnlyThe `break` KeywordThe `continue` KeywordNested LoopsRecap - Repeating Actions2Variables and Basic Data Types
What is a variableType Inference with `:=`Integers (int)Floating-Point NumbersBooleansStringsZero ValuesConstantsNaming ConventionsRecap - Variables and Types5Basic Input/Output
Formatted OutputFormat VerbsPrinting TypesGetting Basic User InputRecap - Input and Output8Functions
Understanding FunctionsDeclaring a FunctionCalling FunctionsFunction ParametersReturning a Single ValueReturning Multiple ValuesNamed Return ValuesFunction Scope BasicsRecap - Creating Reusable Code3Basic Operators
Arithmetic OperatorsDivision OperatorThe Modulo OperatorAssignment OperatorAugmented Assignment OperatorsIncrement and DecrementRecap - Calculations6Control Flow: Conditionals
The `if` StatementThe `else` KeywordThe `else if` KeywordVariable Shadowing in `if`Initializing VariablesThe `switch` StatementSwitch with ExpressionsSwitch without ExpressionThe `fallthrough` KeywordRecap - Making Decisions