Home > Mobile >  Passing parameter to a function parameter is not working
Passing parameter to a function parameter is not working

Time:04-01

I have written the following code.

package main

import (
    "fmt"
    "strings"
)

type student struct {
    Name string
    Age  int
    City string
}

func takeFuncAsParam(a func(st student, c string) bool, s []student) []student {
    var result []student
    for _, e := range s {
        if a(e,c) {
            result = append(result, e)
        }
    }
    return result
}

func main() {
    s1 := student{"Subir", 30, "Bolpur"}
    s2 := student{"Mainak", 29, "Bolpur"}
    s := []student{s1, s2}
    filterByName := func(s student, c string) bool {
        return strings.Contains(s.Name, c)

    }
    result := takeFuncAsParam(filterByName, s)

    fmt.Println(result)
}

i am getting compilation error in line number 17.

    undefined: c

So how can I pass a parameter to filterByName function in this case (c string)?

CodePudding user response:

Change the argument type of takeFuncAsParam to be func(student) bool, i.e. drop the c string parameter, like so:

func takeFuncAsParam(fn func(student) bool, s []student) []student {
    var result []student
    for _, e := range s {
        if fn(e) {
            result = append(result, e)
        }
    }
    return result
}

Change the filterByName to be a function that takes the name argument by which to filter and returns a new function of the type required by takeFuncAsParam, i.e. func(student) bool, like so:

filterByName := func(name string) func(student) bool {
    return func(s student) bool {
        return strings.Contains(s.Name, name)
    }
}

To use the new filter function you need to call it with the name argument by which to filter and then pass the returned function to takeFuncAsParam, like so:

fn := filterByName("Subir")
result := takeFuncAsParam(fn, s)

// or

result := takeFuncAsParam(filterByName("Subir"), s)

https://go.dev/play/p/e3QemrZxB-S

  •  Tags:  
  • go
  • Related