Range Over Built in Julia
On this page
Based on your input, the target language is Julia. Below is the translated Go code into Julia, along with the corresponding explanations.
Range over Built-in Types
range
iterates over elements in a variety of built-in data structures. Let’s see how to use range
with some of the data structures we’ve already learned.
Here we use range
to sum the numbers in an array. Arrays work like this too.
nums = [2, 3, 4]
sum = 0
for num in nums
sum += num
end
println("sum:", sum)
range
on arrays and slices provides both the index and value for each entry. Above we didn’t need the index, so we ignored it. Sometimes we actually want the indexes though.
for (i, num) in enumerate(nums)
if num == 3
println("index:", i)
end
end
range
on dictionaries iterates over key/value pairs.
kvs = Dict("a" => "apple", "b" => "banana")
for (k, v) in kvs
println("$k -> $v")
end
range
can also iterate over just the keys of a dictionary.
for k in keys(kvs)
println("key:", k)
end
range
on strings iterates over Unicode code points. The first value is the starting byte index of the character and the second the character itself.
for (i, c) in enumerate("go")
println(i-1, ' ', c) # (i-1) to convert 1-based index to 0-based
end
To run the program, you can simply use Julia’s interactive session or save the code in a .jl
file and run it using the Julia command:
$ julia range_over_built_in_types.jl
Expected Output:
sum: 9
index: 2
a -> apple
b -> banana
key: a
key: b
0 g
1 o
Next example: Pointers.