Home  >  Article  >  Backend Development  >  Why is the inline function called immediately instead of just its containing function?

Why is the inline function called immediately instead of just its containing function?

王林
王林forward
2024-02-06 08:06:031052browse

Why is the inline function called immediately instead of just its containing function?

Question content

When assigning values ​​to structure fields.

FlagSet: (func() *flag.FlagSet {
        fs := newFlagSet("configure")
        return fs
    })(),

I think it is equivalent to calling newFlagSet("configure"). What are the pros of writing in this manner.

Problems when reading source code. Need to know why he wrote this.


Correct answer


Quick search, this code comes fromtailscale/tailscale, cmd/ tailscale/cli/configure.go#var configureCmd = &ffcli.Command{}

var configureCmd = &ffcli.Command{
    Name:      "configure",
    ShortHelp: "[ALPHA] Configure the host to enable more Tailscale features",
    LongHelp: strings.TrimSpace(`
The 'configure' set of commands are intended to provide a way to enable different
services on the host to use Tailscale in more ways.
`),
    FlagSet: (func() *flag.FlagSet {
        fs := newFlagSet("configure")
        return fs
    })(),
    Subcommands: configureSubcommands(),
    Exec: func(ctx context.Context, args []string) error {
        return flag.ErrHelp
    },
}

This code uses a function literal (anonymous function) and then calls it immediately.

This is called Immediately invoked function expression (IIFE). This is more common in languages ​​like JavaScript, but can be useful in Go as well.

In Go, IIFE allows you to isolate pieces of logic that produce values, creating a scoping environment for variables that does not pollute the surrounding namespace.
Variables used in anonymous functions (fs in this case) are not escaped into the surrounding code. This makes the code easier to reason about because variables only exist when needed.

Although FlagSet: newFlagSet("configure") is true, is equivalent to FlagSet: (func() *flag.FlagSet { fs := newFlagSet("configure"); return fs })(), some advantages of the second form may be:

  • Scalability: If future modifications to newFlagSet("configure") require more complex operations or calculations, these changes can be easily incorporated into the anonymous function without changing configureCmd Structure.
  • Debugging: Encapsulated logic can be easily commented, recorded, or modified during a debugging session without disturbing surrounding code.

Looking at the tailscale code, that particular IIFE usage appears to be limited to that one instance.

The above is the detailed content of Why is the inline function called immediately instead of just its containing function?. 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