# Go.Method + Go.Interface
Presented in Women Who Code, Taipei , 2021
<!-- Put the link to this slide here so people can follow -->
slide: https://hackmd.io/@pieceofr/S1uweajlt
---
This presentation is base on
- [A Tour of Go : Method + Interface Section](https://tour.golang.org/methods/1)
- [簡中版本](https://tour.go-zh.org/welcome/1)
---
## Method & Interface
- NOT a Object Oriented Language (OOP)
- Encapsulation
- Inheritance
- Polymorphism
- Overloading (diff params)
- Overriding (child overides its parent)
- GO has Method + Interface
---
### Method
- 方法(method)即函數(function)
- a function with receiver
- reciever before function name
- 使用 Dot(.) 來操作 receiver
- 限制: Reciever 只能定義在同一個 package
(ps. codes in bottom page)
----
- Method version
```go=
type Vertex struct {X, Y float64}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
```
- Function version
```go=
func Abs(v Vertex) float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
```
----
如何為不是 package 裡的 struct 寫方法 ?
https://tour.golang.org/methods/3
---
### Pointer
- 使用pointer 當 reciever
- func (v *MyStruct) Method1() float64
- 本身不能是 pointer (ie. MyStruct 不能是 pointer)
- 使用 pointer 是可以改變 Reciever的值
- Excercise on https://tour.golang.org/methods/4
- 把 Scale 的 Reciever 變為 struct
- pointer 跟 struct 的不同是 ?
- (2 mins and share)
----
- call indirection
```go
func (v *Vertex) Scale(f float64)
v := Vertex{3, 4}
p := &Vertex{4, 3}
v.Scale() // (&p).Scale()
p.Scale()
```
- go throgh https://tour.golang.org/methods/7 to understand
----
Receiver : Value or Pointer ?
- Pointer
- 改變值
- 避免重複 copy value 更有效率
- Value
- Next Section
---
### Interface
- An interface type is defined as a set of method signatures
- 是由一组方法签名定义的集合
```go=
type I interface {
M()
}
type T struct {S string}
// 此方法表示类型 T 实现了接口 I,但我们无需显式声明此事。
func (t T) M() {
fmt.Println(t.S)
}
func main() {
var i I = T{"hello"}
i.M()
}
```
- Decoupling definition 跟 implementation
----
- 在 Interface 執行方法時 必須是確實的型別
- Interface Vaue 跟特定型別綁定
- https://play.golang.org/p/ciKrbglFF8o
----
interface 要如何處理 reciever 空值!?
(Interface values with nil underlying values)
```go=
var iNil I
var tNil *T
iNil = tNil
iNil.M()
func (t *T) M() { // t = nil 時可以進入程式
if t == nil { // Take care of it
fmt.Println("<nil>")
return
}
fmt.Println(t.S)//如果nil 卻沒處理呼叫 method 會當掉
}
```
----
The empty interface
```interface{}``` 沒有任何方法的 interface
```go=
// fmt.Print
func Println(a ...interface{}) (n int, err error) {
// ...
}
```
---
### Type Assertions
- This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t
```
t := i.(T)
```
or
```
t, ok := i.(T)
```
---
### Type Switch
- A type switch is a construct that permits several type assertions in series
```go=
func do(i interface{}) {
switch v := i.(type) {
case int:
fmt.Printf("Twice %v is %v\n", v, v*2)
case string:
fmt.Printf("%q is %v bytes long\n", v, len(v))
default:
fmt.Printf("I don't know about type %T!\n", v)
}
}
```
---
Excercise: Method and Interface
```
command line program that takes 2 arguments
- flag s : shape string
- Circle/Square
- flag l : length
- 大於 1 -> use the value
- 其他 = 1
- Shape interface
- functions
- Area() float64
- SetLength(l float64)
- Fix PrintArea Function
```
- [Excercise Template](https://replit.com/@PieceofrPai/EexcerciseTemplate#main.go)
- https://replit.com/join/iaupdralvj-pieceofrpai (join-link)
- [Example](https://replit.com/@PieceofrPai/ExcerciseInterfaceMethod)
---
Excercise: Errors
- Sqrt參數小於0 回傳一個自定義的 ErrNegativeSqrt Error
- [Excercise Discription](https://tour.golang.org/methods/20)
- [My Sqrt Solution](https://play.golang.org/p/zd2s0neSXRu)
- [My Excercise Errors](https://play.golang.org/p/g2sgNaQDPtY)
---
### Thank you! :sheep:
You can find me on
- [gitHub](github/pieceofr)
- [email](pieceofr@gmail.com)
{"metaMigratedAt":"2023-06-16T08:03:20.530Z","metaMigratedFrom":"YAML","title":"Go.Method+Go.Interface","breaks":true,"description":"Presentation for Go Method base on A tour Of Go","slideOptions":"{\"theme\":\"solarized\",\"transition\":\"fade\",\"spotlight\":{\"enabled\":true}}","contributors":"[{\"id\":\"4620ae12-2ff3-4233-a7f9-b451b3b42179\",\"add\":7713,\"del\":3346}]"}