惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

SecWiki News
SecWiki News
I
InfoQ
The Cloudflare Blog
人人都是产品经理
人人都是产品经理
博客园 - Franky
T
Tailwind CSS Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
量子位
博客园_首页
罗磊的独立博客
V
V2EX
李成银的技术随笔
大猫的无限游戏
大猫的无限游戏
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
True Tiger Recordings
Vercel News
Vercel News
Cyberwarzone
Cyberwarzone
Cisco Talos Blog
Cisco Talos Blog
F
Fox-IT International blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
M
Microsoft Research Blog - Microsoft Research
Know Your Adversary
Know Your Adversary
爱范儿
爱范儿
The Register - Security
The Register - Security
G
Google Developers Blog
The Hacker News
The Hacker News
Malwarebytes
Malwarebytes
S
Securelist
博客园 - 三生石上(FineUI控件)
Jina AI
Jina AI
T
Threat Research - Cisco Blogs
T
The Exploit Database - CXSecurity.com
S
SegmentFault 最新的问题
博客园 - 叶小钗
F
Fortinet All Blogs
Apple Machine Learning Research
Apple Machine Learning Research
宝玉的分享
宝玉的分享
博客园 - 聂微东
T
Threatpost
博客园 - 【当耐特】
D
Docker
P
Privacy & Cybersecurity Law Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
G
GRAHAM CLULEY
V
Visual Studio Blog
C
Cisco Blogs
IT之家
IT之家
S
Security Archives - TechRepublic
Latest news
Latest news
阮一峰的网络日志
阮一峰的网络日志

ZDDHUB

PixelsMeasure 开发第二年总结 PixelsMeasure 开发一年总结 Swift/SwiftUI 踩坑记 为什么说 GPT 利好程序员 ChatGPT 编程实现 Web 数字水印 Web 数字水印探究 Micro Frontends for Mobile URL 加载系统(URL Loading System) Protocol Buffers GraphQL 从 0 到 1 开发一款 IOS 应用 - Swift MV* 软件设计架构 学习一个新技巧需要多久? 不停机数据库迁移 Rspec 如何 mock update 方法更新自己? Rails 使用 mysql2 出现的段错误 使用 Docker-compose 部署 Rails 应用到生产环境 Cocoa troubleshooting 独孤九剑 Dit (0x05) - 终端篇 Gem-based Jekyll theme 开发小记 Miscellaneous 前端手记 TodoMVC 之 Redux 篇 前端手记 TodoMVC 之 Server 篇 前端手记 TodoMVC 之 React 篇 前端手记 TodoMVC 之 CSS 篇 独孤九剑 Dit (0x04) - 测试篇 独孤九剑 Dit (0x03) - 缓存篇 英语小抄 LLDB debug Golang Make mistakes 大牛俱乐部上线啦 独孤九剑 Dit (0x02) - 数据结构篇 独孤九剑 Dit (0x01) - 总决 独孤九剑 Dit (0x00) - 我为什么要做 Dit 零值强制类型转换的使用 终端颜色输出重定向 Go语法简略 - 正则表达式 Makefile Go语法简略 - Duck框架探索 Go语法简略 - 依赖注入 Go语法简略 - web应用框架 Go语法简略 - 反射 Go语法简略 - 方法和接口 Go语法简略 - goroutine Go语法简略 - 基础篇 大牛 | 轻松科研 为 Android Studio 创建图标 未来这几年 Shell Git Vim 金庸答百问 论拖延症 Flex, A fast scanner generator 有理想的人 从虚拟到现实 常用视频转接口 Recognizer configuration on CentOS 整个世界清静了 《Python源码剖析》读书笔记
Go语法简略 - 面向对象
2015-06-29 · via ZDDHUB

优秀的程序员应该不限于只用一两种语言,对各种语言都要有猎涉,这样才能在合适的应用下选择最合适的语言。但优秀的程序员至少需要精通一到两种语言,在众多的编程语言中,我选择Go和Swift作为自己之后20年内的主要编程语言。

package main

import "fmt"

// Go中没有类,只有struct,Go使用匿名域完成了struct的复用,使用接口完成了类似多态的功能。

type Human struct {
  name  string
  email string
  age   int
}

type Boss struct { // 定义结构
  Human   // 匿名字段, 复用Human结构
  company string
  url     string
  email   string // 重名属性
}

func (h Human) SayHello() {
  fmt.Printf("Hi, I am %s, %d years old, you can contact me via %s.\n", h.name, h.age, h.email)
}

func (h Human) Laugh() {
  fmt.Println("Hahaha ...")
}

func (b Boss) Laugh() { // 重写了SayHello方法
  fmt.Println("Hehehe ...")
}

type Sportor interface { // 定义接口, 接口中包含了一系列方法
  Walk()
  Run(km int)
  // Man string 错误,接口中只能包含方法
  // Method() {} 错误,不能有默认的方法实现
}

type Laugher interface {
  Laugh()
}

type Speaker interface {
  Laugher // 匿名字段,引用Laugher中的方法
  SayHello()
  SayGoodbye()
}

// Boss实现SayGoodbye()
func (b Boss) SayGoodbye() {
  fmt.Println("Goodbye, my employee!")
}

// Human实现Walk方法
func (h *Human) Walk() { // 使用指针可避免拷贝,并且可以修改接受者的值
  fmt.Println("I am walking")
}

// Human实现Run方法
func (h *Human) Run(km int) {
  fmt.Println("Run ", km, "mile")
}

func main() {
  fmt.Println("This is a go lang practice.")
  // 结构复用
  h := Human{"zddhub", "zddhub@gmail.com", 10}
  fmt.Println("Name:", h.name) // 访问属性
  fmt.Println("Age:", h.age)
  fmt.Println("Email:", h.email)
  h.SayHello()
  h.Laugh()

  b := Boss{Human{"daniu", "zddhub@gmail.com", 20}, "daniu.io",
    "www.daniu.io", "daniu@gmail.com"}
  // 不能这样初始化Boss
  // c := Boss{"daniu", "zddhub@gmail.com", 20, "daniu.io",
  //  "www.daniu.io", "daniu@gmail.com"}
  // 也不能这样初始化Boss
  // d := Boss{ {"daniu", "zddhub@gmail.com", 20}, "daniu.io",
  //  "www.daniu.io", "daniu@gmail.com"}

  fmt.Println("Name:", b.name) // 访问属性
  fmt.Println("Age:", b.age)
  fmt.Println("Email:", b.email)             // 重名属性,最外层优先使用
  fmt.Println("Human Email:", b.Human.email) // 用结构名明确访问内层变量
  b.SayHello()                               // 继承Human的SayHello方法
  b.Laugh()                                  // 重写Human的Laugh方法
  b.Human.Laugh()                            // 用结构名明确调用内层方法

  // Go没有像C++一样的继承,所以下面的方法是错误的:
  // var hh *Human
  // hh = &b
  // 这种情况在Go中由接口来实现

  // 接口
  var l Laugher
  l = h // l能存Human
  fmt.Println(l)
  l.Laugh()
  l = b // l能存Boss
  fmt.Println(l)

  x := make([]Laugher, 2)
  x[0], x[1] = h, b // 两个不同类型的元素,实现了同样的接口
  for _, value := range x {
    value.Laugh() // 多态的调用Laugh,显示不同的功能
  }

  var s Speaker
  s = b // b实现了Speaker接口中的所有方法
  s.SayHello()
  s.Laugh()
  s.SayGoodbye()
  // s.name 错误,接口只能调用方法,不能调用属性

  var spt Sportor
  spt = &h
  // spt = h 错误,接收者为指针
  spt.Run(10)
  spt.Walk()

  var a interface{} // a为空接口,可以引用任意类型的数据,如:
  a = h
  a = b
  a = 1
  a = spt
  fmt.Println(a)

  // interface中变量的类型
  list := make([]interface{}, 4)
  list[0], list[1], list[2], list[3] = h, b, 1, spt

  for index, element := range list {
    if value, ok := element.(Human); ok { // 使用类型断言判断
      fmt.Printf("list[%d] is an Human and its value is %v\n", index, value)
    } else if value, ok := element.(Boss); ok {
      fmt.Printf("list[%d] is an Boss and its value is %v\n", index, value)
    } else if value, ok := element.(int); ok {
      fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
    } else if value, ok := element.(*Human); ok {
      fmt.Printf("list[%d] is an *Human and its value is %d\n", index, value)
    }
  }

  // 也可以减少if else的使用,用switch来处理
  for index, element := range list {
    switch value := element.(type) { // element.(type)的语法只能在switch语句之内使用
    case int:
      fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
    case Human:
      fmt.Printf("list[%d] is a Human and its value is %v\n", index, value)
    case Boss:
      fmt.Printf("list[%d] is a Boss and its value is %v\n", index, value)
    default:
      fmt.Printf("list[%d] is of a different type\n", index)
    }
  }
}