Getting the index of an element

Report a typo

Erick has created a function indexOf(). It returns the index of a specific element in a slice of strings:

func indexOf(s []string, e string) int {
    for i, v := range s {
        if v == e {
            return i
        }
    }
    return -1
}

You have suggested Erick make indexOf() a generic function instead, so it can work with slices of int and float64 data types too. However, Erick doesn't know the most basic details about generics!

Can you help Erick write the entire generic implementation of the indexOf() function below? Take notice that to properly solve this task you must not change any code within the main function!

Sample Input 1:

42 777 343
42
3.1416 1.618 2.718
1.618
red green blue
blue

Sample Output 1:

0
1
2
Write a program in Go
package main

import "fmt"

// Your task is to write the entire generic implementation of indexOf()
// Remember to use the same algorithm as in the task statement!
// Also remember that it should only take int, string, and float64 data types!
func indexOf ? {
?
}

// DO NOT MODIFY the code within the main() function!
func main() {
var num1, num2, num3, elem1 int
fmt.Scanln(&num1, &num2, &num3)
fmt.Scanln(&elem1)

var num4, num5, num6, elem2 float64
fmt.Scanln(&num5, &num6, &num4)
fmt.Scanln(&elem2)

var str1, str2, str3, elem3 string
fmt.Scanln(&str1, &str2, &str3)
fmt.Scanln(&elem3)

intSlice := []int{num1, num2, num3}
floatSlice := []float64{num5, num6, num4}
stringSlice := []string{str1, str2, str3}

fmt.Println(indexOf(intSlice, elem1))
fmt.Println(indexOf(floatSlice, elem2))
fmt.Println(indexOf(stringSlice, elem3))
}
___

Create a free account to access the full topic