最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I pass a function as a parameter to another function in Go templates - Stack Overflow

programmeradmin1浏览0评论

I have a custom function using Go templates as follows:

"listOperate": func(lst []string, fn func(string) string) (result []string) {
    result = make([]string, len(lst))
    for i, item := range lst {
        result[i] = fn(item)
    }
    return result
},

I have another function which operates on a string:

"toCamel": func(str string) (result string) {
        return strcase.ToCamel(str)
    }

How can I call the first function, using the second as a parameter?

Copilot gives me the following

{{ listOperate . toCamel}}

which makes sense but fails to parse with the error

at <toCamel>: wrong number of args for toCamel: want 1 got 0" (template.ExecError)

which suggests it is trying to execute the function instead of passing it. Google gives me plenty of information on custom functions but nothing answers this problem.

I have a custom function using Go templates as follows:

"listOperate": func(lst []string, fn func(string) string) (result []string) {
    result = make([]string, len(lst))
    for i, item := range lst {
        result[i] = fn(item)
    }
    return result
},

I have another function which operates on a string:

"toCamel": func(str string) (result string) {
        return strcase.ToCamel(str)
    }

How can I call the first function, using the second as a parameter?

Copilot gives me the following

{{ listOperate . toCamel}}

which makes sense but fails to parse with the error

at <toCamel>: wrong number of args for toCamel: want 1 got 0" (template.ExecError)

which suggests it is trying to execute the function instead of passing it. Google gives me plenty of information on custom functions but nothing answers this problem.

Share Improve this question edited Mar 5 at 17:29 Mr_Pink 110k17 gold badges283 silver badges272 bronze badges asked Mar 5 at 15:43 TaoistTaoist 3831 gold badge4 silver badges11 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 6

There is not a way to name a function without calling the function. The code {{ listOperate . toCamel}} calls toCamel with no arguments.

Write a template function that returns the function:

"toCamelFunc": func() any {
    return func(str string) (result string) {
        return strcase.ToCamel(str)
    }
}

Use it like this: {{ listOperate . toCamelFunc}}

发布评论

评论列表(0)

  1. 暂无评论