go blank identifier _作用

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

The blank identifier has many possible uses, but its main purpose is to allow discarding returns from functions that have multiple returns:

// We only care about the rune and possible error, not its lengthr, _, err := buf.ReadRune()

There are some other fun, but sometimes hackish, uses.

Mark an import or local variable as "used" so that the compiler won't issue an error:

import "fmt"var _ = fmt.Println // now fmt is used and the compiler won't complainfunc main() {    var x int    _ = x // now x is used and the compiler won't complain}

Make sure a type implements an interface at compile time:

var _ InterfaceType = Type{} // or new(Type), or whatever

Ensure that a constant lies within a certain range at compile time:

// Ensure constVal <= 10const _ uint = 10 - constVal// Ensure constVal >= 1 (constVal > UINT_MAX + 1 is also an error)const _ uint = -1 + constVal

Ensure a function parameter is unused:

// This could be useful if somebody wants a value of type// func(int, int) int// but you don't want the second parameter.func identity(x, _ int) int { return x }
golang  sql/driver 裡面有使用:
type noRows struct{}var _ Result = noRows{}
這個就是讓編譯器靜態檢查一個類型是否實現某個介面,這是一種編程技巧.golang的介面是duck模型的,沒有顯示的聲明,某個具體類型鬆散的實現某個介面,通過這層檢查,基本上我們就可以確定某個具體類型實現了某個介面.這也是golang duck介面模型的一個不好的點吧.這是一種輔助編程,加強程式健壯性的手段,理論上不使用這種方法,通過unit test也能保證.Some people use a line like as an interface check. This line ensures that the type noRows implements the Result interface. If it doesn't you will get a compiler error.


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.