Named Function Types Carry Behavior
Declare a named function type, assign funcs and closures to it, compose pipelines from it, and check nil before calling a zero-value variable.
Code
package main
import (
"fmt"
"strings"
)
// 具名函数类型:签名相同的函数可赋值、传递、组合
type Transformer func(string) string
func upper(s string) string { return strings.ToUpper(s) }
func chain(first Transformer, rest ...Transformer) Transformer {
return func(s string) string {
out := first(s)
for _, t := range rest {
out = t(out)
}
return out
}
}
func main() {
var t Transformer // 零值 nil,调用前必须检查
fmt.Println("nil before assignment:", t == nil)
t = upper // 函数名直接赋给同签名类型
t = chain(t, func(s string) string { return "[" + s + "]" })
fmt.Println(t("deploy api"))
registry := map[string]Transformer{"shout": upper}
fmt.Println(registry["shout"]("quiet"))
}How it works
Named Function Types Carry Behavior is built around the functions upper, chain and main.
Iteration happens inside for _, t := range rest — everything outside it runs once.
Putting it to use
The one signature that matters here is func upper(s string) string
The demo output is labeled (nil before assignment:), so the output doubles as a step-by-step trace of what the file did.
The entry point wires chain together — run it once and the whole demo flows.
The core lines of the flow
func upper(s string) string { return strings.ToUpper(s) }
func chain(first Transformer, rest ...Transformer) Transformer {
return func(s string) string {
out := first(s)
for _, t := range rest {
out = t(out)
}
return out
}
}
t = chain(t, func(s string) string { return "[" + s + "]" })
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Named Function Types Carry Behavior print when run?
- Running the file directly is enough — expect labeled output lines such as `nil before assignment:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.