What are mutating functions in Julia?
The concept of mutating functions in Julia is straightforward. A mutating function changes the contents of an array/vector. These functions’ names are suffixed with !.
Note: If the function changes the array reference without changing its content, it’s not a mutating function.
Coding example
Refer to the following example to understand a mutating function. In this example, we’ll create a function that halves every value of the passed vector in place, thus changing the contents of the vector.
function half_each_array_val!(v::Vector{Float64})for ind in eachindex(v)v[ind] = v[ind] / 2endendvec = Vector{Float64}([3, 15, 21, 94])println("Original Vector:")println(vec)half_each_array_val!(vec)println("\nMutated Vector:")println(vec)
Explanation
- Lines 1–5: We define a function named
half_each_array_val!(), which accepts a vector of typefloat64. It will halve every value in the provided vector. - Line 7: We define a vector of float values named
vec. - Line 9: We print the original vector.
- Line 10: We invoke the
half_each_array_val!()function withvecas the argument. - Line 12: We print the mutated vector.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved