SoFunction
Updated on 2025-03-01

Go  import _ Using underline

import _ Underline

When integrating pprof into the project, we only need to add a line of code on it

import _ "net/http/pprof"

Then, start a Go method to listen for the corresponding port

("localhost:6060", nil)

In this way, the function of pprof has been integrated into the project. The underscore import here mainly executes the init() method in pprof.

Methods of init

The method of init in the source code is as follows:

func init() {
  ("/debug/pprof/", Index)
  ("/debug/pprof/cmdline", Cmdline)
  ("/debug/pprof/profile", Profile)
  ("/debug/pprof/symbol", Symbol)
  ("/debug/pprof/trace", Trace)
}

This is why just import can achieve routing registration.

effect

In addition, underscore _ is a special identifier in the go language, and its function also includes:

  •  Ignore variables: When you do not need to use a value returned by a function, you can use an underscore to ignore this value. This is usually used when a function returns multiple values, but you are only interested in some of them.

  • Ignore index or value in for loop: When you don't need to use indexes or values ​​in a loop, you can use underscores to ignore them.

  • Blank identifiers in interface assertions and type conversions: When you make type assertions on an interface type but do not need assertions, you can use underscores.

  • Use in multiple assignments: When you are doing multiple assignments but some variables have been declared and you do not want to use them when assignments, you can use underscores.

The above is the detailed content of the use of Go import underscore_. For more information about Go import_underscore, please follow my other related articles!