What's the purpose of golang allowing multiple init in one package?

Viewed 8120

I know that golang allows multiple init in one package and even in one file. I am wondering why? For example, if a pkg has many files, we could write multiple init then we could get lost in where to we should put init, and we could be also confused about the init order if we have multiple init in one pkg. (I mean is this better? we can only have 1 init, then we can have some initXXX, then put them into init, it seems quite clean.) What's the advantage of doing this in code struct view?

2 Answers

Another use case for multiple init() functions is adding functionality based on build tags. The init() function can be used to add hooks into the existing package and extend its functionality.

The following is a condensed example demonstrating the addition of more commands to a CLI utility based on build tags.

package main

import "github.com/spf13/cobra"

var rootCmd = &cobra.Command{Use: "foo", Short: "foo"}

func init() {
    rootCmd.AddCommand(
        &cobra.Command{Use: "CMD1", Short: "Command1"},
        &cobra.Command{Use: "CMD2", Short: "Command2"},
    )
}

func main() {
    rootCmd.Execute()
}

The above is the "vanilla" version of the utility.

// +build debugcommands

package main

import "github.com/spf13/cobra"

func init() {
    rootCmd.AddCommand(&cobra.Command{Use: "DEBUG-CMD1", Short: "Debug command1"})
}

The contents of the second file extends the standard command with additional commands that are mostly relevant during development.

Compiling using go build -tags debugcommands will produce a binary with the added commands, while omitting the -tags flag will produce a standard version.

Related