5.4 Go语言中自定义类型与结构体(Struct)

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

结构体匿名字段

结构体匿名字段其实是一种类似继承的手段&

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老孙正经胡说

创作不易,感谢您的关注

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值