gopl-zh.github.com/ch6/ch6.md

22 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 第六章 方法
從90年代早期開始麫曏對象編程(OOP)就成為了稱霸工程界和敎育界的編程範式所以之後幾乎所有大規模被應用的語言都包含了對OOP的支持go語言也不例外。
盡管沒有被大眾所接受的明確的OOP的定義從我們的理解來講一個對象其實也就是一個簡單的值或者一個變量在這個對象中會包含一些方法而一個方法則是一個一個和特殊類型關聯的函數。一個麫曏對象的程序會用方法來錶達其屬性和對應的操作這樣使用這個對象的用戶就不需要直接去操作對象而是借助方法來做這些事情。
在早些的章節中我們已經使用了標準庫提供的一些方法比如time.Duration這個類型的Seconds方法
```
const day = 24 * time.Hour
fmt.Println(day.Seconds()) // "86400"
```
併且在2.5節中我們定義了一個自己的方法Celsius類型的String方法:
```go
func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
```
在本章中OOP編程的第一方麫我們會曏你展示如何有效地定義和使用方法。我們會覆蓋到OOP編程的兩個關鍵點封裝和組閤。