Home > Enterprise >  golang using functools.partial or similar to accomplish wrapping other functions
golang using functools.partial or similar to accomplish wrapping other functions

Time:01-09

(new to golang)

Let's say I have two functions that interact with an API underneath and I'd like to wrap both with retries but these two functions have different input params.

In Python I would use functools.partial to create a partial func object and pass that in

from functools import partial

def api_1(a, b, c):
  print(a, b, c)
  return true
  
def api_2(x, y):
  print(x, y)
  return true

def with_retries(func) {
  retries = 0
  while retries < 3:
    err = func()
    if not err:
      break
    retries  = 1
}

def main():
  with_retries(partial(api_1, 1, 2, 3))
  with_retries(partial(api_2, 'x', 'y'))

Using the simple example above, how could I do something similar in golang? I looked at the functools.Partial package function but that one seems like it does not allow to pass in all of the parameters when creating a partial?

Is there a completely different pattern in golang to accomplish this retry pattern?

CodePudding user response:

If I understand functools.Partial correctly, it allows you to curry functions.

In Go you can use closures to curry functions:

func Add(x,y int) int {
  return x y
}
// Curries Add to yield a function that adds 4
func Add4(y int) int {
  return Add(4,y)
}

Go supports first-class functions, so you can pass functions as variables. In this case we create a function Do that accepts (a) any function that's int-->int and (b) an int and returns the result of applying the function to the int:

func Do(f func(int) int, y int) int {
    return f(y)
}

And, because Do only needs int-->int we can use e.g. Neg too per:

package main

import "fmt"

func Add(x, y int) int {
    return x   y
}
func Add4(y int) int {
    return Add(4, y)
}

func Neg(x int) int {
    return -x
}

func Do(f func(int) int, y int) int {
    return f(y)
}
func main() {
    fmt.Println(Add4(6))
    fmt.Println(Do(Add4, 6))
    fmt.Println(Do(Neg, 6))
}

See: https://go.dev/play/p/4ZkIpvYTxC0

  •  Tags:  
  • go
  • Related