面試企業(yè) 百度
解析整理 GOLANG ROADMAP社區(qū)
答案(溪尾)
對于Go語言是否像C++抡四、Java一樣是面向?qū)ο蟮恼Z言柜蜈,官方給出的解釋如下:
Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy. The concept of “interface” in Go provides a different approach that we believe is easy to use and in some ways more general. There are also ways to embed types in other types to provide something analogous—but not identical—to subclassing. Moreover, methods in Go are more general than in C++ or Java: they can be defined for any sort of data, even built-in types such as plain, “unboxed” integers. They are not restricted to structs (classes).
Also, the lack of a type hierarchy makes “objects” in Go feel much more lightweight than in languages such as C++ or Java.
翻譯:
是,也不是.雖然Go語言可以通過定義類型和方法來實現(xiàn)面向?qū)ο蟮脑O(shè)計風格,但是Go實際上并沒有繼承這一說法.在Go語言中,interface(接口)這個概念以另外一種角度展現(xiàn)了一種更加易用與通用的設(shè)計方法.在Go中,我們可以通過組合,也就是將某個類型放入另外的一個類型中來實現(xiàn)類似繼承,讓該類型提供有共性但不相同的功能.相比起C++和Java,Go提供了更加通用的定義函數(shù)的方法,我們可以指定函數(shù)的接受對象(receiver),它可以是任意的類型,包括內(nèi)建類型,在這里沒有任何的限制。
同樣的,沒有了類型繼承,使得Go語言在面向?qū)ο缶幊痰姆矫鏁@得更加輕量化指巡。
在Go語言中跨释,可以通過結(jié)構(gòu)體組合來實現(xiàn)繼承,示例如下:
// 這里Student繼承了People厌处,具有People的屬性
type People struct {
Name string
}
type Student struct{
People
Grade int
}
本文由 GOLANG ROADMAP 發(fā)布!