Related Tags

rust
array
length
communitycreator

# Finding the length of an array in Rust

okwudili onyejiaku

## Overview

The length of an array is the number of elements present in the array. We use the len() function to obtain this value.

### Syntax

array.len()
Syntax to obtain the length of an array in Rust

### Parameters

This method has no defined parameters.

### Return value

The value returned is an integer representing the total count of elements present in the given array.

### Example

// main function
fn main(){
// create some arrays
let numbers = [5,10,15];
let animals = ["cat","dog","fox","koala"];
let letters = ["A","B","C","D","E"];
let ages:[i32;5] = [10,22,30,4,18];

// print length of arrays
println!("Length of numbers array: {}", numbers.len());
println!("Length of animals array: {}", animals.len());
println!("Length of letters array: {}", letters.len());
println!("Length of ages array: {}", ages.len());
}
Code to obtain the length of an array in Rust

### Explanation

• Line 4–7: We create some arrays.
• Line 10–13: Obtain the lengths of the arrays and print them on the console.
Note: ages:[i32;5] on line 7 means that the array is of 32-bit integer type and has a length of 5.

RELATED TAGS

rust
array
length
communitycreator

CONTRIBUTOR

okwudili onyejiaku
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time