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

王林
Release: 2024-02-06 10:15:07
forward
953 people have browsed it

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'))
Copy after login

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)
}
Copy after login

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)
}
Copy after login

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))
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!