Array Length with `len`
Part of the Fundamentals section of Coddy's GO journey — lesson 71 of 109.
The len() function returns the length (number of elements) of an array.
Create an array of colors:
colors := [4]string{"Red", "Blue", "Green", "Yellow"}Get the array length using len():
arrayLength := len(colors)
fmt.Println("The array has", arrayLength, "elements")This displays:
The array has 4 elementsChallenge
Beginnerlen() function to find the length of an array.We've provided an array of favorite fruits. Your task is to find the length of this array using the
len() function and store it in the numberOfFruits variable.Cheat sheet
The len() function returns the length (number of elements) of an array:
colors := [4]string{"Red", "Blue", "Green", "Yellow"}
arrayLength := len(colors)
fmt.Println("The array has", arrayLength, "elements")Output:
The array has 4 elementsTry it yourself
package main
import "fmt"
func main() {
// This is our array of favorite fruits
favoriteFruits := [5]string{"Apple", "Banana", "Orange", "Mango", "Strawberry"}
// TODO: Use the len() function to find the length of the favoriteFruits array
// and store it in the numberOfFruits variable
var numberOfFruits int
// This will print the number of fruits in the array
fmt.Printf("There are %d fruits in the array\n", numberOfFruits)
}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 Actions10Composite Types: Arrays
Introduction to ArraysDeclaring ArraysInitializing ArraysAccessing Array ElementsArray Length with `len`Iterating Over ArraysMulti-dimensional Arrays2Variables 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