小能豆

How to access parameter of a function passed as a parameter

go

Is there a way to access a parameter of a function passed as a parameter?

package main

import (
    "context"
    "log"
)

type Context *context.Context

type PaymentProcessor func(ctx *Context, gateway string) (bool, error)

func Order(p PaymentProcessor) (string, error) {
    // Access p(ctx)

    // Access p(gateway)?
    return "", nil
}

func MCPaymentProcessor(ctx *Context, gateway string) (bool, error) {
    // Do something
    return false, nil
}

func main() {
    orderNumber, err := Order(MCPaymentProcessor)
    if err != nil {
        log.Fatalf("failed to process order: %v", err)
    }
    if orderNumber == "" {
        log.Println("failed to process order")
    } else {
        log.Printf("order: %s", orderNumber)
    }
}

I’m unable to access the context or gateway for the function passed as a parameter


阅读 67

收藏
2023-12-19

共1个答案

小能豆

In Go, you can’t directly access the parameters of a function that is passed as an argument. However, you can achieve what you want by modifying the signature of your PaymentProcessor function type to include the context and gateway parameters explicitly, like this:

package main

import (
    "context"
    "log"
)

type PaymentProcessor func(ctx context.Context, gateway string) (bool, error)

func Order(p PaymentProcessor) (string, error) {
    // Access p(ctx) and p(gateway) directly
    ctx := context.TODO() // You might want to use a proper context here
    result, err := p(ctx, "someGateway")
    if err != nil {
        return "", err
    }

    if result {
        return "success", nil
    } else {
        return "failure", nil
    }
}

func MCPaymentProcessor(ctx context.Context, gateway string) (bool, error) {
    // Do something
    return false, nil
}

func main() {
    orderNumber, err := Order(MCPaymentProcessor)
    if err != nil {
        log.Fatalf("failed to process order: %v", err)
    }

    log.Printf("order: %s", orderNumber)
}

Now, when you call p(ctx, "someGateway") inside the Order function, you are passing the context and gateway explicitly to the function, and you can access them directly within the function.

2023-12-19