Golang program that takes in a slice of integers and an anonymous function that maps each element in the slice to a new value


In this article, we will write Go language programs that take in a slice of integers and an anonymous function that maps each element in the slice to a new value. An anonymous function is declared without a name and is assigned to a variable which is called to execute the process.

Syntax

func make ([] type, size, capacity)

The make function in go language is used to create an array/map it accepts the type of variable to be created, its size and capacity as arguments.

func range(variable)

The range function is used to iterate over any data type. To use this, we first have to write the range keyword followed by the data type to which we want to iterate and as a result the loop will iterate till the last element of the variable.

Algorithm

  • This program imports the main and fmt as necessary packages.

  • Create a main function.

  • In the main, initialize a slice with some values and the slice name is kept as values.

  • Initialize the values slice with the desired integers.

  • In this step, define an anonymous mapping function with an integer n as an argument.

  • In the function, use the mapped value of n as n*2.

  • Then, apply the mapping using the map function.

  • Call the map function, pass the values slice and the anonymous mapping function as arguments.

  • Then, store the returned new slice of mapped values in a variable called new values.

  • Print the mapped values stored in new values using the Println function from the fmt package where ln means new line.

Example

In this example, we will write a Go language program to map each element in the slice to a new value using an anonymous function which displays values as n*2.

package main

import (
	"fmt"
)
func main() {	
	values := []int{1, 2, 3, 4, 5}
	fmt.Println("The initial values are:", values)	
	newvalues := Map(values, func(n int) int {
		return n * 2
	})	
	fmt.Println("The new mapped values are:")
	fmt.Println(newvalues) 
}
func Map(values []int, fn func(int) int) []int {
	mappedvalues := make([]int, len(values))
	for i, val := range values {
		mappedvalues[i] = fn(val)
	}
	return mappedvalues
}

Output

The initial values are: [1 2 3 4 5]
The new mapped values are:
[2 4 6 8 10]

Conclusion

We compiled and executed the program of taking in a slice of integers and mapping it to new values using an anonymous function.

Updated on: 04-Aug-2023

55 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements