home‎ > ‎go‎ > ‎

go function pointers

Go language handles function pointers very elegantly, therefore I love it better than 'C'.

Here is a Hello world example for function pointer in golang.

package main

import (
    "fmt"
)

type Transform func(in string) (out string, cascade bool)

func Hello(in string) (out string, cascade bool) {
    out = "Hello "+in
    return out, true
}

func print(xf Transform, in string) {
    t,b := xf(in)
    fmt.Println(t,b)
}
func main() {
    print(Hello, "Ashish")
    
}

Try this at Go Playground...

Next, I tested out the function pointer map.


package main

import (

    "fmt"

)


type Transform func(in string) (out string, cascade bool)


var XMap map[string] Transform = make(map[string] Transform)


func init() {

  XMap["HASH"] = Hello

}


func Hello(in string) (out string, cascade bool) {

    out = "Hi "+in

    return out, true

}


func Default(in string) (out string, cascade bool) {

    out = "Default: "+in

    return out, true

}


func print(fname, in string) {

    var xf Transform =  Default

    x := XMap[fname]

    if x != nil {

        xf = x

    } 

    t,b := xf(in)

    fmt.Println(t,b)

}

func main() {

    print("HASH", "Ashish")    

}


Check this out at Go Playground...

I will now demonstrate use of array of function pointers.


package main


import (

"fmt"

)


type Transform func(in string) (out string, cascade bool)


var XArr []Transform


func init() {


XArr = []Transform{Hello, Default}

}


func XForm(in string) (out string, cascade bool) {

out = in

for _, fx := range XArr {

out, cascade = fx(out)

if !cascade {

break

}

}

return out, false

}

func Hello(in string) (out string, cascade bool) {

out = "Hi " + in

return out, true

}


func Default(in string) (out string, cascade bool) {

out = "Default: " + in

return out, true

}


func print(in string) {

var xf Transform = XForm

t, b := xf(in)

fmt.Println(t, b)

}

func main() {

print("Ashish")


}


Comments