最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Go?interface?接口的最佳實踐經驗分享

 更新時間:2022年04月15日 10:13:42   作者:西京刀客  
go?的接口在go的編程里面用的十分頻繁,尤其是空接口的使用,因為有了接口,才使得Go語言變得異常的強大,今天給大家介紹下Go?interface?接口的最佳實踐經驗分享,感興趣的朋友一起看看吧

Go語言-Go 接口的最佳實踐

原文連接:https://blog.boot.dev/golang/golang-interfaces/

Go 中的接口允許我們暫時將不同的類型視為相同的數(shù)據類型,因為這兩種類型實現(xiàn)相同的行為。它們是Go程序員工具箱的核心,并且經常被新的Go開發(fā)人員不正確地使用,導致代碼不可讀且經常有錯誤。

什么是Golang中的interface

In Go, an interface is a custom type that other types are able to implement, which gives Go developers a powerful way to use abstraction. Interfaces are named collections of method signatures, and when other types implement all the required methods, they implicitly implement the interface.

在 Go 中,接口是其他類型可以實現(xiàn)的自定義類型,這為 Go 開發(fā)人員提供了使用抽象的強大方式。接口是方法簽名的集合,當其他類型實現(xiàn)所有需要的方法時,它們隱式地實現(xiàn)了接口。

例如,Go 中的errors是接口,標準error接口很簡單,一個類型要被認為是error,所需要做的就是定義一個 Error ()方法,該方法不接受任何參數(shù),并返回一個字符串。

type error interface {
    Error() string
}

錯誤error的簡單性使得編寫日志和metrics 實現(xiàn)更加容易。讓我們定義一個表示網絡問題的結構體:

type networkProblem struct {
	message string
	code    int
}

然后我們可以定義一個 Error ()方法:

func (np networkProblem) Error() string {
	return fmt.Sprintf("network error! message: %s, code: %v", np.message, np.code)
}

現(xiàn)在,我們可以在接受錯誤的任何地方使用 networkProblem struct 的實例。

func handleErr(err error) {
	fmt.Println(err.Error())
}
np := networkProblem{
	message: "we received a problem",
	code:    404,
}
handleErr(np)
// prints "network error! message: we received a problem, code: 404"

編寫接口的最佳實踐

編寫干凈的接口是困難的。坦率地說,任何時候你都在處理代碼中的抽象,如果你不小心的話,簡單可以很快變成復雜。讓我們回顧一下保持interfaces整潔的一些經驗法則。

  • Keep interfaces small 保持interfaces足夠小
  • Interfaces should have no knowledge of satisfying types 接口應該沒有令人滿意的類型的知識
  • Interfaces are not classes 接口不是類

1. 保持interfaces足夠小

If there is only one piece of advice that you take away from this article, make it this: keep interfaces small! Interfaces are meant to define the minimal behavior necessary to accurately represent an idea or concept.

如果您從本文中只得到了一條建議,那就是: 保持接口小一些!接口意味著定義精確表示一個想法或概念所需的最小行為。

下面是一個大型接口的標準 HTTP package的例子,它是定義最小行為的一個很好的例子:

type File interface {
    io.Closer
    io.Reader
    io.Seeker
    Readdir(count int) ([]os.FileInfo, error)
    Stat() (os.FileInfo, error)
}

Any type that satisfies the interface’s behaviors can be considered by the HTTP package as a File. This is convenient because the HTTP package doesn’t need to know if it’s dealing with a file on disk, a network buffer, or a simple []byte.

任何滿足接口行為的類型都可以被 HTTP package 視為File。這很方便,因為 HTTP package 不需要知道它是在處理磁盤上的文件、還是網絡緩沖區(qū)或是[]byte。

2. Interfaces Should Have No Knowledge of Satisfying Types

An interface should define what is necessary for other types to classify as a member of that interface. They shouldn’t be aware of any types that happen to satisfy the interface at design time.

接口應該定義其他類型作為該接口的成員所必需的內容。他們不應該知道在設計時為了滿足接口而發(fā)生的任何類型。

例如,假設我們正在構建一個接口來描述定義汽車所必需的構成元素。

type car interface {
	Color() string
	Speed() int
	IsFiretruck() bool
}

Color() and Speed() make perfect sense, they are methods confined to the scope of a car. IsFiretruck() is an anti-pattern. We are forcing all cars to declare whether or not they are firetrucks. In order for this pattern to make any amount of sense, we would need a whole list of possible subtypes. IsPickup(), IsSedan(), IsTank()… where does it end??

Color()Speed()非常合理,它們是限制在汽車范圍內的方法。IsFiretruck ()是一個反模式。我們正在強制所有的汽車申報它們是否是消防車。為了使這個模式具有任何意義,我們需要一個可能的子類型的完整列表。IsPickup () ,IsSedan () ,IsTank () … 它在哪里結束?

Instead, the developer should have relied on the native functionality of type assertion to derive the underlying type when given an instance of the car interface. Or, if a sub-interface is needed, it can be defined as:

相反,當給定汽車接口的實例時,開發(fā)人員應該依賴于類型斷言的原生功能來派生基礎類型?;蛘?,如果需要子接口,可以將其定義為:

type firetruck interface {
	car
	HoseLength() int
}

它繼承了汽車所需的方法,并增加了一個額外的所需方法,使汽車一輛消防車。

3. 接口不是類

  • Interfaces are not classes, they are slimmer. 接口不是類,它們更小
  • Interfaces don’t have constructors or deconstructors that require that data is created or destroyed. 接口沒有要求創(chuàng)建或銷毀數(shù)據的構造函數(shù)或解構函數(shù)
  • Interfaces aren’t hierarchical by nature, though there is syntactic sugar to create interfaces that happen to be supersets of other interfaces. 接口本質上并不具有層次性,盡管在創(chuàng)建恰好是其他接口的超集的接口時存在語法糖
  • Interfaces define function signatures, but not underlying behavior. Making an interface often won’t 接口定義函數(shù)簽名,但不定義底層行為。制作interface通常不會在結構方法方面不干擾您的代碼。例如,如果五種類型滿足錯誤接口,那么它們都需要自己的版本的Error() function. 函數(shù)

有關接口的更多信息

空的接口

空接口沒有指定任何方法,因此 Go 中的每個類型都實現(xiàn)了空接口。

interface{}

It’s for this reason that developers sometimes use a map[string]interface{} to work with arbitrary JSON data, although I recommend using anonymous structs instead where possible.

出于這個原因,開發(fā)人員有時使用 map[string]interface{}來處理任意 JSON 數(shù)據,盡管我推薦在可能的情況下使用匿名結構。

Zero value of an interface

Interfaces can be nil, in fact, it’s their zero value. That’s why when we check for errors in Go, we’re always checking if err != nil, because err is an interface.

接口可以是 nil,事實上,這是它們的零值。這就是為什么當我們在 Go 中檢查錯誤時,我們總是檢查err != nil,因為 err 是一個接口。

指針上的接口

It’s a common “gotcha” in Go to implement a method on a pointer type and expect the underlying type to implement the interface, it doesn’t work like that.

在 Go 中,在指針類型上實現(xiàn)一個方法并期望底層類型實現(xiàn)接口是一個常見的“明白了”,它不是這樣工作的。

type rectangle interface {
    height() int
    width() int
}

type square struct {
    length int
}

func (sq *square) width() int {
    return sq.length
}

func (sq *square) height() int {
    return sq.length
}

Though you may expect it to, in this example the square type does not implement the rectangle interface. The *square type does. If I wanted the square type to implement the rectangle interface I would just need to remove the pointer receivers.

雖然您可能希望這樣做,但是在這個示例中,正方形類型不實現(xiàn)矩形接口。它使用的是*square。如果我想讓正方形類型實現(xiàn)矩形接口,我只需要刪除指針接收器。

type rectangle interface {
    height() int
    width() int
}

type square struct {
    length int
}

func (sq square) width() int {
    return sq.length
}

func (sq square) height() int {
    return sq.length
}

到此這篇關于Go interface 接口的最佳實踐的文章就介紹到這了,更多相關Go interface 接口內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

读书| 浪卡子县| 太仓市| 丰顺县| 儋州市| 星座| 蒙城县| 内黄县| 长岛县| 宜宾县| 亚东县| 博野县| 方山县| 富裕县| 姜堰市| 西乌| 页游| 巩义市| 芒康县| 宿松县| 延吉市| 台北市| 恩平市| 山阴县| 山阴县| 涞源县| 平谷区| 兴安盟| 彭水| 屏东市| 铅山县| 平定县| 七台河市| 尼木县| 堆龙德庆县| 扶绥县| 日土县| 拉孜县| 灵宝市| 余姚市| 宁河县|