9

Blank identifier (underscore)

 3 years ago
source link: https://yourbasic.org/golang/underscore/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Blank identifier (underscore)

yourbasic.org/golang
ignore-this-text.jpg

The blank identifier _ is an anonymous placeholder. It may be used like any other identifier in a declaration, but it does not introduce a binding.

Ignore values

The blank identifier provides a way to ignore left-hand side values in an assignment.

_, present := timeZone["CET"]

sum := 0
for _, n := range a {
	sum += n
}

Import for side effects

It can also be used to import a package solely for its side effects.

import _ "image/png" // init png decoder function

Silence the compiler

It can be used to during development to avoid compiler errors about unused imports and variables in a half-written program.

package main

import (
    "fmt"
    "log"
    "os"
)

var _ = fmt.Printf // DEBUG: delete when done

func main() {
    f, err := os.Open("test.go")
    if err != nil {
        log.Fatal(err)
    }
    _ = f // TODO: read file
}

For an automatic solution, use the goimports tool, which rewrites a Go source file to have the correct imports. Many Go editors and IDEs run this tool automatically.

Share:             


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK