Go是面向对象的语言吗
在很多文章中都提到,Go语言中的struct某种意义就是对应其他语言中的class,就该问题特意阅读了Go语言官网的常见问题,有这样的描述
Is Go an object-oriented language?
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语言变得更轻。
类型定义
使用type字段进行自定义类型的定义,基本结构为type 。
下面这个例子是一个利用结构体定义的新类型。
package main
import "fmt"
type NameAge struct {
name string // Both non exported fields.
age int
}
func main() {
a := new(NameAge)
a.name = "Pete"
a.age = 42
fmt.Printf("struct values = %v\n", a)
fmt.Printf("struct full = %+v\n", a)
fmt.Printf("struct a.name = %s\n", a.name)
}
输出结果为,如果使用%v只输出值而不输出字段,使用%+v,可以同时输出字段,如果访问其中的值,则使用.的方式
struct values = &{
Peter 42}
struct full = &{
name:Peter age:42}
struct a.name = Peter
结构体匿名字段
结构体匿名字段其实是一种类似继承的手段&