Home  >  Article  >  Backend Development  >  golang uses functools.partial or similar methods to complete wrapping other functions

golang uses functools.partial or similar methods to complete wrapping other functions

王林
王林forward
2024-02-06 10:15:07968browse

golang 使用 functools.partial 或类似的方法来完成包装其他函数

Question content

(golang newbie)

Suppose I have two functions that interact with the underlying api, and I want to wrap these two functions with retry, but the two functions have different input parameters.

In python I would use functools.partial to create a partial func object and pass it to

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 can I do something similar in golang? I looked at the functools.partial package function but that function doesn't seem to allow passing all arguments when creating a partial function?

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


Correct answer


If I understand correctly functools.partial, 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 example, we create a function do that accepts (a) any int-->int function and (b) int and returns The result of this function applied to int:

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

Also, since do only requires int-->int we can use e.g. neg also as follows:

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://www.php.cn/link/7a43ed4e82d06a1e6b2e88518fb8c2b0 p>

The above is the detailed content of golang uses functools.partial or similar methods to complete wrapping other functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete