【Day 22】Go 基础小笔记 III :method / interface

没有 object、没有 class 、没有继承的 Go,
靠着 struct / method / interface,
好像也享有 OOP 语言的优点呢

今天的笔记依然参考 30天学会Golang 系列,
以及相见恨晚的 A Tour of Go(互动式教学,有 compiler)

明天会是最後一篇小笔记,毕竟 Go 是并发(concurrency)小能手,
还是要了解一下 Goroutines。
之後想想做点实际的 hands on 之类。

method

本来以为 Go 是物件导向,後来发现没有 class
基本上使用 struct 与 method 来达到类似的效果。

method 是一个有 receiver argument 的 function
we can define method on a type. (不一定是 struct,但这个 type 要在同个 package 中,int 这些 built-in type 要先透过 type 关键字来定义一个新型别才能用,例如 type myint int

// 定义 Vertex struct
type Vertex struct {
	X, Y float64
}
// Abs method
func (v Vertex) Abs() float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
	v := Vertex{3, 4}
    // 使用 method 时就像别的语言使用一个 class 内ㄉ function 一样
	fmt.Println(v.Abs())
}

  • receiver argument 的型别很重要!golang 会依据他的型别帮忙转~
    所以如果这个 method 要改值,记得在 receiver 那边写好是吃 pointer(打星星)
// v *Vertex 这样就算下面的 v 并不是一个 pointer,go 也会帮忙转 &v
func (v *Vertex) Scale(f float64) { 
	v.X = v.X * f
	v.Y = v.Y * f
}
func main() {
    // 如果拿掉上面 receiver 的*,也可以在这边 &Vertex{3, 4}
	v := Vertex{3, 4}
    // 或是 (&v).Scale(10)
	v.Scale(10)
}

interface

Go 里 interface 是一个型别,里面有定义一堆 method signatures,
只要合乎这些签章的数值(通常是 struct)就可以放进这个介面变数。
如果这个变数没有实作规定的 method 的话,就会喷错。

  • empty interface
    没有定义任何 method 的 interface 当作 input 的型别,就可以接受任意型别的 input。

以下例子来自day15 - 介面(续)
empty interface + 以 type 为不同 case 的 switch

func main() {
	printAnyType(2020)
	printAnyType("Iron Man")
	printAnyType(0.25)
}

// 定义一个函式,接收任何型别,并且格式化输出值
func printAnyType(i interface{}) {
	switch v := i.(type) {
	case int:
		fmt.Printf("case int: %d \n", v)
	case string:
		fmt.Printf("case string: %s \n", v)
	default:
		fmt.Printf("default: %v \n", v)
	}
}

没有继承

毕竟没有 class,也没有继承的概念。
而是使用 struct 中包 struct,称之为 composition。
go 中还能使用 embbeded,这里不打了。
day13 - 内嵌


<<:  Day 23:Ansible 的基本介绍

>>:  Day 23 - WooCommerce: 建立信用卡付款订单 (上)

自动化 End-End 测试 Nightwatch.js 之踩雷笔记:点击物件

点击特定物件是 E2E 中很常会做到的事,如果本身物件有设定好特定的 ID, Class 或 Att...

@Day30 | C# WixToolset + WPF 帅到不行的安装包 [最终回]

哈哈, 其实拖了很久了! 今天来把最後剩下功能给补齐,修复跟移除, 只是我在看InstallView...

例行监督表单撰写实务

上一篇内部稽核讲到 5. 监督作业:进行下列监督作业,以确定本制度之有效性、及时性及确实性: (1)...

ASP.NET MVC 从入门到放弃 (Day5) -C# 判断式 回圈介绍

接着来讲讲常用的判断式写法.... 简单来说以下就是玩攻略游戏 在选择选项的逻辑.... 单项if写...

每日挑战,从Javascript面试题目了解一些你可能忽略的概念 - Day2

tags: ItIron2021 Javascript 前言 昨天我们透过了一个相当经典的题目探讨了...