Golang underline summary

Time:2020-11-1

Today, when I look at the gin framework, I used a render package when tracking gin when processing the interface return. In the process of looking at the code, I found such a writing method:

// Render interface is to be implemented by JSON, XML, HTML, YAML and so on.
type Render interface {
    // Render writes data with custom ContentType.
    Render(http.ResponseWriter) error
    // WriteContentType writes custom ContentType.
    WriteContentType(w http.ResponseWriter)
}

var (
    _ Render     = JSON{}
    _ Render     = IndentedJSON{}
    _ Render     = SecureJSON{}
    _ Render     = JsonpJSON{}
    _ Render     = XML{}
    _ Render     = String{}
    _ Render     = Redirect{}
    _ Render     = Data{}
    _ Render     = HTML{}
    _ HTMLRender = HTMLDebug{}
    _ HTMLRender = HTMLProduction{}
    _ Render     = YAML{}
    _ Render     = Reader{}
    _ Render     = AsciiJSON{}
    _ Render     = ProtoBuf{}
)

It looks strange at first sight_ What’s the point of the author’s writing? Render is an interface type in the code, and this assignment implicitly implements the type assertion of the interface: whether the data type on the right implements the interface type on the left, if not, a compilation error will be reported.

This kind of writing method is quite stable, which can be used for reference in subsequent development. What are the other uses in go_ The scene?

Ignore the return value of the function

This is the most common way to use it. In the traversal of a for loop, you can often see:

for _, v := range result {
    
}

It is also common to ignore the return value of a function.

Use when importing packages

Occasionally, when importing packets, there are the following methods:

import _ "githu.com/think-next"

This way is to execute the init function within the package. This package is of no use to our code, except for its internal init method.