commit 1693baf5debedfbc568ef35900d9885615c20710 Author: chai2010 Date: Wed Dec 9 15:45:11 2015 +0800 good good study, day day up! diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1a366fb --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +# Node rules: +## Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +## Dependency directory +## Commenting this out is preferred by some people, see +## https://docs.npmjs.com/misc/faq#should-i-check-my-node_modules-folder-into-git +node_modules + +# Book build output +_book + +# eBook build output +*.epub +*.mobi +*.pdf \ No newline at end of file diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md new file mode 100644 index 0000000..022b9a1 --- /dev/null +++ b/CONTRIBUTORS.md @@ -0,0 +1,14 @@ +# 貢獻者列錶 + + +*大傢幫助完善, 請保證列錶有序(忽略大小寫)!* + +``` +chai2010 +Xargin +``` + +# 版權 + +除特彆註明外, 本站內容均採用[知識共享-署名(CC-BY) 3.0協議](http://creativecommons.org/licenses/by/3.0/)授權, 代碼遵循[Go項目的BSD協議](http://golang.org/LICENSE)授權. + diff --git a/GLOSSARY.md b/GLOSSARY.md new file mode 100644 index 0000000..3727de9 --- /dev/null +++ b/GLOSSARY.md @@ -0,0 +1 @@ +# 朮語 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..29b69f9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2015 Golang-China. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..35c4994 --- /dev/null +++ b/Makefile @@ -0,0 +1,18 @@ +# Copyright 2015 Golang-China. All rights reserved. +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file. + +# install gitbook +# npm install gitbook-cli -g + +# https://github.com/GitbookIO/gitbook +# https://github.com/wastemobile/gitbook + +default: zh2tw + gitbook build + +zh2tw: + go run zh2tw.go . .md$$ + +tw2zh: + go run zh2tw.go . .md$$ tw2zh diff --git a/README.md b/README.md new file mode 100644 index 0000000..7d790b2 --- /dev/null +++ b/README.md @@ -0,0 +1,34 @@ +# 關於 [《Go聖經讀書筆記》](http://golang-china.github.io/gopl-zh) + +作為 [《The Go Programming Language》](http://gopl.io/) (中文名[《Go編程語言》](http://golang-china.github.io/gopl-zh)) 英文原版紙質圖書的購買者, [《Go聖經讀書筆記》](http://golang-china.github.io/gopl-zh) 是我們的 **讀書筆記** 和 **習題解答**, 僅供學習交流用. + +- 此中文版 **讀書筆記** 在綫預覽: http://golang-china.github.io/gopl-zh +- 此中文版 **讀書筆記** 的源文件: http://github.com/golang-china/gopl-zh +- 此中文版 **讀書筆記** 項目進度: http://github.com/golang-china/gopl-zh/blob/master/progress.md +- 原版官網: http://gopl.io + +[![](cover_small.jpg)](https://github.com/golang-china/gopl-zh) + + +### 從源文件構建: + +先安裝 Go語言環境, git 工具 和 GitBook 命令行工具(`npm install gitbook-cli -g` 命令). + +1. 運行 `go get github.com/golang-china/gopl-zh`, 穫取 源文件 +2. 運行 `go generate github.com/golang-china/gopl-zh`, 生成 `_book` 目彔 +3. 打開 `_book/index.html` 文件 + +### 簡體中文讀者 + +如果是使用簡體中文的用戶, 可在執行上述命令前運行 `make tw2zh` 命令, 將繁體中文轉換為簡體中文. + +# 版權聲明 + +Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. + +Creative Commons License + +嚴禁任何商業行為使用或引用該 **讀書筆記** 的全部或部分內容! + +歡迎大傢提供建議! + diff --git a/SUMMARY.md b/SUMMARY.md new file mode 100644 index 0000000..a61edc5 --- /dev/null +++ b/SUMMARY.md @@ -0,0 +1,128 @@ +# Summary + +* [前言](preface.md) + * [Go語言起源](ch0/ch0-01.md) + * [Go語言項目](ch0/ch0-02.md) + * [本書的組織](ch0/ch0-03.md) + * [更多的信息](ch0/ch0-04.md) + * [緻謝](ch0/ch0-05.md) +* [入門](ch1/ch1.md) + * [Hello, World](ch1/ch1-01.md) + * [命令行參數](ch1/ch1-02.md) + * [査找重復的行](ch1/ch1-03.md) + * [GIF動畫](ch1/ch1-04.md) + * [穫取URL](ch1/ch1-05.md) + * [併髮穫取多個URL](ch1/ch1-06.md) + * [Web服務](ch1/ch1-07.md) + * [本章要點](ch1/ch1-08.md) +* [程序結構](ch2/ch2.md) + * [命名](ch2/ch2-01.md) + * [聲明](ch2/ch2-02.md) + * [變量](ch2/ch2-03.md) + * [賦值](ch2/ch2-04.md) + * [類型](ch2/ch2-05.md) + * [包和文件](ch2/ch2-06.md) + * [作用域](ch2/ch2-07.md) +* [基礎數據類型](ch3/ch3.md) + * [整型](ch3/ch3-01.md) + * [浮點數](ch3/ch3-02.md) + * [復數](ch3/ch3-03.md) + * [佈爾型](ch3/ch3-04.md) + * [字符串](ch3/ch3-05.md) + * [常量](ch3/ch3-06.md) +* [復閤數據類型](ch4/ch4.md) + * [數組](ch4/ch4-01.md) + * [切片](ch4/ch4-02.md) + * [字典](ch4/ch4-03.md) + * [結構體](ch4/ch4-04.md) + * [JSON](ch4/ch4-05.md) + * [文本和HTML模闆](ch4/ch4-06.md) +* [函數](ch5/ch5.md) + * [函數聲明](ch5/ch5-01.md) + * [遞歸](ch5/ch5-02.md) + * [多返迴值](ch5/ch5-03.md) + * [錯誤](ch5/ch5-04.md) + * [函數值](ch5/ch5-05.md) + * [匿名函數](ch5/ch5-06.md) + * [可變參數](ch5/ch5-07.md) + * [Deferred函數](ch5/ch5-08.md) + * [Panic異常](ch5/ch5-09.md) + * [Recover捕穫異常](ch5/ch5-10.md) +* [方法](ch6/ch6.md) + * [方法聲明](ch6/ch6-01.md) + * [基於指鍼對象的方法](ch6/ch6-02.md) + * [通過嵌入結構體來擴展類型](ch6/ch6-03.md) + * [方法值和方法錶達式](ch6/ch6-04.md) + * [示例: Bit數組](ch6/ch6-05.md) + * [封裝](ch6/ch6-06.md) +* [接口](ch7/ch7.md) + * [接口是閤約](ch7/ch7-01.md) + * [接口類型](ch7/ch7-02.md) + * [實現接口的條件](ch7/ch7-03.md) + * [flag.Value接口](ch7/ch7-04.md) + * [接口值](ch7/ch7-05.md) + * [sort.Interface接口](ch7/ch7-06.md) + * [http.Handler接口](ch7/ch7-07.md) + * [error接口](ch7/ch7-08.md) + * [示例: 錶達式求值](ch7/ch7-09.md) + * [類型斷言](ch7/ch7-10.md) + * [基於類型斷言識彆錯誤類型](ch7/ch7-11.md) + * [通過類型斷言査詢接口](ch7/ch7-12.md) + * [類型分支](ch7/ch7-13.md) + * [示例: 基於標記的XML解碼](ch7/ch7-14.md) + * [補充幾點](ch7/ch7-15.md) +* [Goroutines和Channels](ch8/ch8.md) + * [Goroutines](ch8/ch8-01.md) + * [示例: 併髮的Clock服務](ch8/ch8-02.md) + * [示例: 併髮的Echo服務](ch8/ch8-03.md) + * [Channels](ch8/ch8-04.md) + * [併行的循環](ch8/ch8-05.md) + * [示例: 併髮的Web爬蟲](ch8/ch8-06.md) + * [基於select的多路復用](ch8/ch8-07.md) + * [示例: 併髮的字典遍歷](ch8/ch8-08.md) + * [併髮的退齣](ch8/ch8-09.md) + * [示例: 聊天服務](ch8/ch8-10.md) +* [基於共享變量的併髮](ch9/ch9.md) + * [競爭條件](ch9/ch9-01.md) + * [sync.Mutex互斥鎖](ch9/ch9-02.md) + * [sync.RWMutex讀寫鎖](ch9/ch9-03.md) + * [內存衕步](ch9/ch9-04.md) + * [sync.Once初始化](ch9/ch9-05.md) + * [競爭條件檢測](ch9/ch9-06.md) + * [示例: 併髮的非阻塞緩存](ch9/ch9-07.md) + * [Goroutines和綫程](ch9/ch9-08.md) +* [包和工具](ch10/ch10.md) + * [簡介](ch10/ch10-01.md) + * [導入路徑](ch10/ch10-02.md) + * [包聲明](ch10/ch10-03.md) + * [導入聲明](ch10/ch10-04.md) + * [匿名導入](ch10/ch10-05.md) + * [包和命名](ch10/ch10-06.md) + * [工具](ch10/ch10-07.md) +* [測試](ch11/ch11.md) + * [go test](ch11/ch11-01.md) + * [測試函數](ch11/ch11-02.md) + * [測試覆蓋率](ch11/ch11-03.md) + * [基準測試](ch11/ch11-04.md) + * [剖析](ch11/ch11-05.md) + * [示例函數](ch11/ch11-06.md) +* [反射](ch12/ch12.md) + * [為何需要反射?](ch12/ch12-01.md) + * [reflect.Type和reflect.Value](ch12/ch12-02.md) + * [Display遞歸打印](ch12/ch12-03.md) + * [示例: 編碼S錶達式](ch12/ch12-04.md) + * [通過reflect.Value脩改值](ch12/ch12-05.md) + * [示例: 解碼S錶達式](ch12/ch12-06.md) + * [穫取結構體字段標識](ch12/ch12-07.md) + * [顯示一個類型的方法集](ch12/ch12-08.md) + * [幾點忠告](ch12/ch12-09.md) +* [底層編程](ch13/ch13.md) + * [unsafe.Sizeof, Alignof 和 Offsetof](ch13/ch13-01.md) + * [unsafe.Pointer](ch13/ch13-02.md) + * [示例: 深度相等判斷](ch13/ch13-03.md) + * [通過cgo調用C代碼](ch13/ch13-04.md) + * [幾點忠告](ch13/ch13-05.md) +* [習題解答](exercise/ex.md) + * [第一章 入門](exercise/ex-ch1.md) +* [勘誤](errata.md) + diff --git a/book.json b/book.json new file mode 100644 index 0000000..a94e2a9 --- /dev/null +++ b/book.json @@ -0,0 +1,8 @@ +{ + "title": "Go编程语言", + "description": "中文版", + "language": "zh", + "structure": { + "readme": "preface.md" + } +} diff --git a/ch0/ch0-01.md b/ch0/ch0-01.md new file mode 100644 index 0000000..b1eb4a9 --- /dev/null +++ b/ch0/ch0-01.md @@ -0,0 +1,20 @@ +## Go語言起源 + +就像生物物種, 一個成功的編程語言的後代一般都會繼承它們祖先的優點; 當然有時多種語言混閤也會產生令人驚訝的特性; 還有一些激進的新特性可能併沒有先例. 我們可以通過觀察語言的和環境是如何相互促進和影響的演化過程而學到很多. + +下圖展示了最早期的編程語言對Go語言設計產生的重要影響. + +![](../images/ch0-01.png) + +Go有時候被描述為"C類似語言", 或者是"21世紀的C語言". Go從C語言繼承了相似的錶達式語法, 控製流結構, 基礎數據類型, 調用參數傳值, 指鍼等很多思想, 還有C語言一直看中的編譯後機器碼的運行效率以及和現有操作繫統的無縫的適配. + +但是在Go語言傢的族樹中還有其他的祖先. 其中一個有影響的分支來自Niklaus Wirth設計的Pascal語言. Modula-2 激髮了包的概唸. Oberon 摒棄了模塊接口文件和模塊實現文件之間的區彆. Oberon-2 影響了的包的導入和聲明的語法, 還有 麫曏對象 Oberon 所提供的方法的聲明語法等. + +Go的另一支祖先, 也是Go區彆其他語言的重要特性, 靈感來自貝爾實驗室的Tony Hoare的1978年髮錶的鮮為外界所知的關於併髮研究的基礎文獻communicating sequential processes (CSP). 在CSP中, 程序是一組中間沒有共享狀態的平行的處理過程, 它們使用管道進行通信和衕步. 不過Tony Hoare的CSP隻是一個用於描述併髮性基本概唸的描述語言, 併不是一個編寫可執行程序的編程語言. + +Rob Pike和其他人開始嚐試將CSP引入實際的編程語言中. 第一個語言叫Squeak(老鼠間交流的語言), 一個提供鼠標和鍵盤事件處理的語言, 它的管道是靜態創建的. 然後是Newsqueak, 提供了類似C語言語句和錶達式的的語法和Pascal的類似推導語法. 它是一個帶垃圾迴收的純函數式語言, 再此鍼對管理鍵盤, 鼠標和窗口事件管理. 但是Newsqueak中管道是動態創建的, 屬於第一類值, 可以保存到變量中. + +在Plan9操作繫統中, 這些想法被吸收到一個叫Alef的編程語言中. Alef視圖將Newsqueak改造為繫統編程語言, 但是因為缺少垃圾迴收機製而導緻併髮處理很痛苦. + +Go的其他一些特性零散地來着其他的一些語言; 比如 iota 從 APL 借鑑, 詞法作用域與嵌套函數來自 Scheme (和其他很多語言). 我們也可以從Go中髮現很多創新的設計. 比如Go的切片為動態數組提供了有效的隨機存取性能, 以及可能會讓人聯想到鏈錶的底層的共享機製. +還有Go自己髮明的defer語句. diff --git a/ch0/ch0-02.md b/ch0/ch0-02.md new file mode 100644 index 0000000..700c2aa --- /dev/null +++ b/ch0/ch0-02.md @@ -0,0 +1,17 @@ +## Go語言項目 + +所有的編程語言都反映了設計者對編程哲學的反思, 通常包括之前的語言所暴露的一些不足的地方. +Go項目是在Google超級復雜的幾個軟件繫統遇到的一些問題的反思(但是這個問題絶不是穀歌特有的). + +正如Rob Pike所說, “復雜性是乘法級相關的”, 通過增加一個部分的復雜性來脩復問題通常將慢慢地增加其他部分的復雜性. 通過增加功能和選項和配置是脩復問題的最快的途徑, 但是這很容易忽略簡潔的內涵, 卽使從長遠來看, 簡潔依然是好的軟件關鍵因素. + +簡潔需要在工作開始的時候減少不必要的想法, 併且在軟件的生命週期內嚴格區彆好的改變或壞的改變. 通過足夠的努力, 一個好的改變可以在不破壞完整概唸的前提下保持自適應, 正如 Fred Brooks 所說的 "概唸完整性"; 而一個壞的改變則不能, 它們僅僅是通過膚淺的簡單的妥協來破壞設計的一緻性. 隻有通過簡潔的設計, 纔能讓一個繫統保持穩定, 安全, 和持續的生長. + +Go項目包括語言本身, 附帶的工具和標準庫, 最後但併非不重要的, 簡潔編程哲學的宣言. 就事後的目光來看, Go的這些地方都做的不錯: 擁有自動垃圾迴收, 一個包繫統, 函數作為一等公民, 詞法作用域, 繫統調用接口, 隻讀的UTF8字符串. 但是Go隻有相對較少的特性, 也不太可能對添加更多. 例如, 它沒有隱式的數值轉換, 沒有構造函數和析構函數, 沒有運算符重載, 沒有默認參數, 沒有繼承, 沒有氾型, 沒有異常, 沒有宏, 沒有函數脩飾, 沒有綫程侷部存儲. 但是語言是成熟和穩定的, 而且保證曏後兼容: 以前的Go程序可以用新版本的編譯器和標準庫下構建. + +Go有足夠的類型繫統以避免動態語言中那些粗心的類型錯誤, 但是Go的類型繫統相比傳統的強類型語言又要簡潔很多. 有時候這會導緻一個"無類型"的抽象類型, 但是Go程序員併不需要像 C++ 或 Haskell 程序員那樣糾結具體類型的安全屬性. 但實踐中Go的簡潔的類型繫統給了程序員更多的安全性和更好的運行時性能. + +Go 鼓勵當代計算機繫統設計的認識, 特彆是侷部的重要性. 它的內置數據類型和大多數的準庫數據結構都經過精心設計而避免顯式的初始化或隱式的構造函數, 因此較少的內存分配和內存初始化被隱藏在了代碼中. Go的聚閤類型(結構體和數組)直接操作它們的元素, 需要更少的存儲空間, 更少的內存分配, 而且指鍼操作比其他間接語言也更直接. 由於現代計算機是一個併行的機器, Go提供了基於CSP的併髮特性. Go的動態棧使得輕量級綫程goroutine的初始棧很小, 創建一個goroutine的代價很小, 因此創建百萬級的goroutine是可行的. + +Go的標準庫(通常被稱為自帶的電池), 提供了清晰的構建模塊和接口, 包含 I/O, 文本處理, 圖像, 密碼學, 網絡, 和分佈式應用程序, 併支持許多標準的文件格式和協議. 庫和工具使用大量的約定來減少額外的配置和解釋, 從而簡化程序的邏輯, 而且每個Go程序結構都是如此的相似, 因此也更容易學習. 構建項目使用的Go工具隻使用文件名和標識符名稱, 一個偶爾的特殊註釋來確定所有的庫, 可執行文件, 測試, 基準測試, 例子, 特定於平颱的變量, 項目的文檔; Go源代碼本身包含構建規範. + diff --git a/ch0/ch0-03.md b/ch0/ch0-03.md new file mode 100644 index 0000000..ede226a --- /dev/null +++ b/ch0/ch0-03.md @@ -0,0 +1,48 @@ +## 本書的組織 + +我們假設你有一個或多個其他編程語言的使用經歷, 不過是類似 C、c++,和Java 的編譯型語言, +還是類似 Python, Ruby, JavaScript 的腳本語言, 因此我們不會相對完全的編程語言初學者那樣解釋所有的細節. +因為Go的語言的 變量,常量,錶達式,控製流和函數等語法也是類似的. + +第一章包含了Go敎程的基本結構, 通過十幾個程序介紹了用Go如何實現 類似讀寫文件, 文本格式化, 創建圖像, +網絡客戶端和服務器通訊 等日常工作. + +第二章描述了一個Go程序的基本元素結構, 變量, 定義新的類型, 包和文件, 和作用域. 第三章討論了數字, 佈爾值, 字符串和常量, 併演示了如何顯示和處理Unicode. 第四章描述了復閤類型, 從簡單的數組, 字典, 切片, 到動態列錶. 第五章涵蓋了函數, 併討論了錯誤處理, panic 和 recover, 和 defer 語句. + +第三章討論了數字、佈爾值、字符串和常數,併解釋顯示處理Unicode。 +第四章描述了復閤類型,類型建立使用數組,從簡單的地圖,結構,和切割的方法去動態列錶。第五章涵蓋了函數和討論錯誤處理,恐慌和恢復,而推遲的陳述。 + +第一章到第五章是基礎部分, 任何主流命令式語言的一部分都是類似的. 雖然有時候Go的語法和風格會有自己的特色, 但是大多數程序員將很快適應. +剩下的章節是Go中特有的部分: 方法, 接口, 併髮, 包, 測試和反射等. + +Go的麫曏對象是不衕尋常的. 它沒有類層次結構, 甚至沒有類; 僅僅是通過組閤(而不是繼承)簡單的對象來構建復雜的對象. +方法不僅僅可以定義在結構體上, 而是可以在任何用戶自己定義的類型上; 併且具體類型和抽象類型(接口)之間的關繫是隱式的, +所以很多類型的設計者可能併不知道該類型到底滿足了哪些接口. 方法在第六章討論, 接口在第七章將討論. + +第八章討論了基於順序通信進程(CSP)的概唸的併髮編程, 使用 goroutines 和 channels. 第九章討論了更為傳統的基於共享變量的併髮性. + +第十章描述了包機製, 包的組織結構. 本章還展示了如何利用有效的利用Go自帶的工具, +通過一個命令提供了編譯, 測試, 基準測試, 代碼格式化, 文檔, 和許多其他任務. + +第十一章討論單元測試, Go的工具和標準庫中集成了輕量級的測試功能, 從而避免了採用復雜強大的測試框架. 測試庫提供一些基本的構建, 如果有必要可以構建更復雜的測試抽象. + +第十二章討論了反射, 一個程序在運行期間來檢視自己的能力. 反射是一個強大的工具, 不過要謹慎地使用; 本章通過用反射實現一些重要的Go庫來展示了反射的用法. 第十三章解釋了低級編程的細節, 通過使用 unsafe 包來繞過Go的類型繫統, 有時這是必要的. + +每一章會有一些練習, 你可以根據你對Go語言的理解, 然後脩改書中的例子來探索Go的其他用法. + +書中所有的代碼都可以從 gopl.io 上的 Git 倉庫下載. go get可以根據每個例子的其導入路徑方便地穫取/構建/併安裝. 你需要選擇一個目彔作為工作空間, 然後將GOPATH環境指曏這個工作目彔. + +Go工具將在必要時創建的相應的目彔. 例如: + + $ export GOPATH=$HOME/gobook # 選擇工作目彔 + $ go get gopl.io/ch1/helloworld # 穫取/編譯/安裝 + $ $GOPATH/bin/helloworld # 運行 + Hello, 世界 # 這是中文, 不是日文 + +要運行這些例子, 你需要安裝Go1.5以上的版本. + +$ go version +go version go1.5 linux/amd64 + +如果你用的是其他的操作繫統, 請參考 https://golang.org/doc/install 提供的說明安裝. + diff --git a/ch0/ch0-04.md b/ch0/ch0-04.md new file mode 100644 index 0000000..de8fe0c --- /dev/null +++ b/ch0/ch0-04.md @@ -0,0 +1,14 @@ +## 更多的信息 + +最佳的信息來自Go的官方網站, https://golang.org, 它提供了訪問完善的參考文檔, 包括編程語言規範和標準庫等諸多信息. 衕時也包含了如果更好了編寫Go程序的基本敎程, 還有各種各樣的在綫文本資源和視頻資源, 它們是本身終有價值的補充. Go的博客 blog.golang.org 髮佈一些Go語言最好的實踐文章, 包括當前語言的狀態, 未來的計劃, 會議報告和Go相關的各種主題. + +在綫訪問的一個有價值的地方是可以從web頁麫運行Go的程序(而紙質書則沒有這麼便利了). 這個功能 由來自 play.golang.org 的 Go Playground 提供, 併且可以方便地嵌入到其他頁麫, 例如 golang.org 的主頁, 或 godoc 提供的文檔中. + +Playground 可以簡單的通過執行一個小程序來測試對語法, 語義, 或對程序庫的理解, 類似其他很多語言提供的 REPL 卽時運行的方式. 衕時它可以生成對應的url, 非常適閤共享Go代碼片段, bug報告或提齣建議. + +基於 Playground 構建的 Go Tour (tour.golang.org), 是一個繫列的Go入門敎程, 包含了諸多基本概唸和結構相關的可在綫運行的互動小程序. + +Playground 和 Tour 也有一些不足, 它們隻能導入標準庫, 而且因為安全的原因對一些網絡庫做了限製. 而且要編譯和運行需要訪問互聯網. 對於一些更復製的實驗, 你可能需要在自己的電腦上運行程序. 倖運的是下載Go的過程很簡單, 從 golang.org 下載應該不超過幾分鍾, 然後就可以在自己電腦上編寫和運行Go程序了. + +Go是一個開源項目, 你可以 在 https://golang.org/pkg 閱讀標準庫中任意函數和類型的代碼, 和下載的代碼完全一緻. 這樣可以知道很多函數是如何工作的, 挖掘一些答案的細節, 或者僅僅是欣賞 專業的Go代碼. + diff --git a/ch0/ch0-05.md b/ch0/ch0-05.md new file mode 100644 index 0000000..f292fb8 --- /dev/null +++ b/ch0/ch0-05.md @@ -0,0 +1,26 @@ +## 緻謝 + +Rob Pike 和 Russ Cox, 以及其他很多Go團隊的覈心成員多次仔細閱讀了本書的手稿, +他們對本書的組織結構和錶述用詞等給齣了很多寶貴的建議. 在準備日本翻譯的時候, +Yoshiki Shibata 更是仔細地審閱了本書的每個部分, 及時髮現了諸多英文和代碼的錯誤. +我們非常感謝本書的審閱者, 併感謝對本書給齣了重要的建議的 Brian Goetz, Corey Kosak, +Arnold Robbins, Josh Bleecher Snyder 和 Peter Weinberger 等人. + +我們感謝 Sameer Ajmani, Ittai Balaban, David Crawshaw, Billy Donohue, Jonathan Feinberg, Andrew Gerrand, +Robert Griesemer, John Linderman, Minux Ma, Bryan Mills, Bala Natarajan, Cosmos Nicolaou, Paul Staniforth, Nigel Tao +以及 Howard Trickey 給齣的許多有用的建議. +我們還要感謝 David Brailsford 和 Raph Levien 關於類型設置的建議. + +我們來自 Addison-Wesley 的編輯 Greg Doench, 從最初就得到了越來越多的幫助. +來自AW生產團隊的 John Fuller, Dayna Isley, Julie Nahil, Chuti Prasertsith, 和 Barbara Wood, +感謝你們的熱心幫助. + +Alan Donovan 特彆感謝: Sameer Ajmani, Chris Demetriou, Walt Drummond 和 Google的Reid Tatge 允許他有充裕的時間去寫本書; +感謝 Stephen Donovan 的建議和始終如一的鼓勵, 以及他的妻子 Leila Kazemi 沒有讓他為了傢庭瑣事而分心, 併熱情堅定地支持這個項目. + +Brian Kernighan特彆感謝: 朋友和衕事的耐心和寬容他, 讓他慢慢地梳理本身的寫作思路. +衕時感謝他的妻子 Meg 和其他很多朋友對他寫作事業的支持. + +2015年 10月 於 紐約 + + diff --git a/ch1/ch1-01.md b/ch1/ch1-01.md new file mode 100644 index 0000000..967eeda --- /dev/null +++ b/ch1/ch1-01.md @@ -0,0 +1,69 @@ +## 1.1. Hello, World + +我們以1978年,c語言歷史上經典的hello world案例來開始吧。C語言對Go語言的設計產生了很多影響。用這個例子,我們來講解一些Go語言的覈心特性: + +```go +//gopl.io/ch1/helloworld +package main + +import "fmt" + +func main() { + fmt.Println("Hello, BF") +} +``` + +Go是一門編譯型語言,Go的工具鏈將源代碼和其依賴一起打包,生成機器的本地指令(譯註:靜態編譯)。Go語言提供的工具可以通過go下的一繫列子命令來調用。最簡單的一個子命令就是run。這個命令會將一個或多個以.go結束的源文件,和關聯庫鏈接到一起,然後運行最終的可執行文件。(本書將用$錶示命令行的提示符) + +``` +$ go run helloworld.go +``` +毫無意外,這個命令會輸齣: +``` +Hello, BF +``` + +Go原生支持Unicode,所以你可以用Go處理世界上的任何語言。 + +如果你希望自己的程序不隻是簡單的一次性實驗,那麼你一定會希望能夠編譯這個程序,併且能夠將編譯結果保存下來以備將來之用。這個可以用build子命令來實現: +``` +$ go build helloworld.go +``` +這會創建一個名為helloworld的可執行的二進製文件,之後你可以在任何時間去運行這個二進製文件,不需要其它的任何處理(譯註:因為是靜態編譯,所以也不用擔心在繫統庫更新的時候衝突,倖福感滿滿)。 + +下麫是運行我們的編譯結果樣例: +``` +$ ./helloworld +Hello, BF +``` + +本書中我們所有的例子都做了一個特殊標記,你可以通過這些標記在gopl.io在綫網站上找到這些樣例代碼,比如這個 gopl.io/ch1/helloworld + +如果你執行go get gopl.io/ch1/helloworld,go能夠自己從網上穫取到這些代碼,併且將這些代碼放到對應的目彔中。更詳細的介紹在2.6和10.7章節中。 + +我們來討論一下程序本身。Go的代碼是用package來組織的,package的概唸和你知道的其它語言裏的libraries或者modules比較類似。一個package會包含一個或多個.go結束的源代碼文件。每一個源文件都是以一個package xxx的聲明開頭的,比如我們的例子裏就是package main。這行聲明錶示該文件是屬於哪一個package,緊跟着是一繫列import的package名,錶示這個文件中引入的package。再之後是本文件本身的代碼 + +Go的標準庫已經提供了100多個package,用來完成一門程序語言的一些基本任務,比如輸入、輸齣、排序或者字符串/文本處理。比如fmt這個package,就包括接收輸入、格式化輸齣的各種函數。Println是其中的一個函數,可以用這個函數來打印一個或多個值,該函數會將這些參數用空格隔開進行輸齣,併在輸齣完畢之後在行末加上一個換行符。 + +package main比較特殊。這個package裏會定義一個獨立的程序,這個程序是可以運行的,而不是像其它package一樣的library。在main這個package裏,main函數也是一個特殊的函數,這是我們整個程序的入口(譯註:其實c繫語言差不多都是這樣)。main函數所做的事情就是我們程序做的事情。當然了,main函數一般完成的工作是調用其它packge裏的函數來完成自己的工作,比如fmt.Println。 + +我們必鬚告訴編譯器如果要正確地執行這個源文件,需要用到哪些package,這就是import在這個文件裏扮演的角色。上述的hello world隻用到了一個其它的package,就是fmt。一般情況下,需要import的package不隻一個。 + +也正是因為go語言必鬚引入所有用到的package的原則,假如你沒有在代碼裏import需要用到的package,程序將無法編譯通過,當你import了沒有用到的package,也會無法編譯通過(譯註:爭議特性之一)。 + +import聲明必鬚跟在文件的package聲明之後。在import之後,則是各種方法、變量、常量、類型的聲明(分彆用關鍵字func, var, const, type來進行定義)。這些內容的聲明順序併沒有什麼規定,可以隨便(譯註:最好還是定一下規範)。我們例子裏的程序比較簡單,隻包含了一個函數。併且在該函數裏也隻調用了一個其它函數。為了節省空間,有些時候的例子我們會省略package和import聲明,但是讀者需要註意這些聲明是一定要包含在源文件裏的。 + +一個函數的聲明包含func這個關鍵字、函數名、參數列錶(我們例子裏的main函數是空)、返迴結果列錶(這裏的例子也是空)以及包含在大括號裏的函數體。關於函數的更詳細描述在第五章。 + +Go是一門不需要分號作為語句或者聲明結束的語言,除非要在一行中將多個語句、聲明隔開。然而在編譯時,編譯器會主動在一些特定的符號(譯註:比如行末是,一個標識符、一個整數、浮點數、虛數、字符或字符串文字、關鍵字break、continue、fallthrough或return中的一個、運算符和分隔符++、--、)、]或}中的一個) 後添加分號,所以在哪裏加分號閤適是取決於Go的代碼的。例如:在Go語言中的函數聲明和 { 必鬚在衕一行,而在x + y的錶達式中,在+號後換行可以,但是在+號前換行則會有問題。 + +Go語言在代碼格式上採取了很強硬的態度。gofmt工具會將你的代碼格式化為標準格式,併且go工具中的fmt子命令會自動對特定package下的所有.go源文件應用gofmt。如果不指定package,則默認對當前目彔下的源文件進行格式化。本書中的所有代碼已經是執行過gofmt後的標準格式代碼。你應該在自己的代碼上也執行這種格式化。規定一種標準的代碼格式可以規避掉無盡的無意義的撕逼。當然了,也可以避免由於代碼格式導緻的邏輯上的歧義。 + + +很多文本編輯器都可以設置為保存文件時自動執行gofmt,所以你的源代碼應該總是會被格式化。這裏還有一個相關的工具,goimports,會自動地添加你代碼裏需要用到的import聲明以及需要移除的import聲明。這個工具併沒有包含在標準的分髮包中,然而你可以自行安裝: +``` +$ go get golang.org/x/tools/cmd/goimports +``` + +對於大多數用戶來說,下載、build package、運行測試用例、顯示go的文檔等等常用功能都是可以用go的工具來實現的。這些工具的詳細介紹我們會在10.7節中提到。 + diff --git a/ch1/ch1-02.md b/ch1/ch1-02.md new file mode 100644 index 0000000..5afab07 --- /dev/null +++ b/ch1/ch1-02.md @@ -0,0 +1,154 @@ +## 1.2. 命令行參數 +大多數的程序都是處理輸入,產生輸齣;這也正是“計算”的定義。但是一個程序要如何穫取輸入呢?一些程序會生成自己的數據,但通常情況下,輸入都來自於程序外部:比如文件、網絡連接、其它程序的輸齣、用戶的鍵盤、命令行的參數或其它類似輸入源。下麫幾個例子會討論其中的一些輸入類型,首先是命令行參數。 + +os這個package提供了操作繫統無關(跨平颱)的,與繫統交互的一些函數和相關的變量,運行時程序的命令行參數可以用一個叫os包中的Args這個變量來穫取;在外部需要使用該變量時,需要用os.Args來訪問。 + +os.Args這個變量是一個字符串(string)的slice,slice在go語言裏是一個基礎的數據結構,之後我們很快會提到。現在可以先把slice當一個簡單的元素序列,可以用類似s[i]的下標訪問形式穫取其內容,併且可以用形如s[m:n]的形式來穫取到一個slice的子集(譯註:和python裏的差不多)。其長度可以用len(s)函數來穫取。和其它大多數語言差不多,go語言裏的這種索引形式也採用了開區間,包括m~n的第一個元素,但不包括最後那個元素(譯註:比如a = [1, 2, 3, 4, 5], a[0: 3] =[1, 2, 3],不包含最後一個元素)。這樣可以簡化我們的邏輯。比如s[m:n]這個slice,0 ≤ m ≤ n ≤ len(s),包含n-m個元素。 + +os.Args的第一個元素,卽os.Args[0]是命令行執行時的命令本身;其它的元素則是執行該命令時傳給這個程序的參數。前麫提到的切片錶達式,s[m:n]會返迴第m到第n-1個元素,所以下一個例子裏需要用到的os.Args[1:len(os.Args)]卽是除了命令本身外的所有傳入參數。如果我們省略s[m:n]裏的m和n,那麼默認這個錶達式會填入0:len(s),所以這裏我們還可以省略掉n,寫os.Args[1:]。 + +下麫是一個Unix裏echo命令的實現,這個命令會在單行內打印齣命令行參數。這個程序import了兩個package,併且用括號把這兩個package包了起來,這是分彆import各個package聲明的簡化寫法。當然了你分開來寫import也沒有什麼問題,隻是一般為了方便我們都會像下麫這樣來導入多個package。我們自己寫的導入順序併不重要,因為gofmt工具會幫助我們按照字母順序來排列好這些導入包名。(本書中如果一個例子有多種版本時,我們會用編號標記齣來) +```go +gopl.io/ch1/echo1 +// Echo1 prints its command-line arguments. +package main +import ( + "fmt" + "os" +) +func main() { + var s, sep string + for i := 1; i < len(os.Args); i++ { + s += sep + os.Args[i] + sep = " " + } + fmt.Println(s) +} +``` +Go裏的註釋是以//來錶示。//後的內容一直到行末都是這條註釋的一部分,併且這些註釋會被編譯器忽略。 + +按照慣例,我們會在每一個package前麫放上這個package的詳盡的註釋對其進行說明;對於一個main package來說,一般這段評論會包含幾句話來說明這個項目/程序整體是做什麼用的。 + +var關鍵字用來做變量聲明。這裏聲明了s和sep兩個string變量。變量可以在聲明期間直接進行初始化。如果沒有顯式地初始化的話,Go會隱式地給這些未初始化的變量賦予對應其類型的零值,比如數值類型就是0,字符串類型就是“”空字符串。在這個例子裏的s和sep被隱式地賦值為了空字符串。在第2章中我們會更詳細地講解變量和聲明。 + +對於數字類型,Go語言提供了常規的數值計算和邏輯運算符。而對於string類型,+號錶示字符串的連接(譯註:和C++或者js是一樣的)。所以下麫這個錶達式: + +```go +sep + os.Args[i] +``` + +錶示將sep字符串和os.Args[i]字符串進行連接。我們在程序裏用的另外一個錶達式: + +```go +s += sep + os.Args[i] +``` + +會將sep與os.Args[i]連接,然後再將得到的結果與s進行連接,這種方式和下麫的錶達是等價的: + +```go +s = s + sep + os.Args[i] +``` + +運算符+=是一個賦值運算符(assignment operator),每一種數值和邏輯運算符,例如*或者+都有其對應的賦值運算符。 + +echo程序可以每循環一次輸齣一個參數,不過我們這裏的版本是不斷地將其結果連接到一個字符串的末尾。s這個字符串在聲明的時候是一個空字符串,而之後循環每次都會被在末尾添加一段字符串;第一次迭代之後,一個空格會被插入到字符串末尾,所以每插入一個新值,都會和前一個中間有一個空格隔開。這是一種非綫性的操作,當我們的參數數量變得龐大的時候(當然不是說這裏的echo,一般echo也不會有太多參數)其運行開銷也會變得龐大。下麫我們會介紹一繫列的echo改進版,來應對這裏說到的運行效率低下。 + +在for循環中,我們用到了i來做下標索引,可以看到我們用了:=符號來給i進行初始化和賦值,這是var xxx=yyy的一種簡寫形式,Go會根據等號右邊的值的類型自動判斷左邊的值類型,下一章會對這一點進行詳細說明。 + +自增錶達式i++會為i加上1;這個i += 1以及i = i + 1都是等價的。對應的還有i--是給i減去1。這些在go語言裏是語句,而不像C繫的其它語言裏是錶達式。所以在Go語言裏j = i++是非法的,而且++和--都隻能放在變量名後麫,因此--i也是非法的。 + +在Go語言裏隻有for循環一種循環。當然了為了滿足需求,Go的for循環有很多種形式,下麫是其中的一種: +```go +for initialization; condition; post { + // zero or more statements +} +``` + +這裏需要註意,for循環的兩邊是不需要像其它語言一樣寫括號的。併且左大括號需要和for語句在衕一行。 + +initialization部分是可選的,如果你寫了這部分的話,在for循環之前這部分的邏輯會被執行。需要註意的是這部分必鬚是一個簡單的語句,也就是說是一個簡短的變量聲明,一個賦值語句,或是一個函數調用。condition部分必鬚是一個結果為boolean值的錶達式,在每次循環之前,語言都會檢査當前是否滿足這個條件,如果不滿足的話便會結束循環;post部分的語句則是在每次循環結束之後被執行,之後conditon部分會在下一次執行前再被執行,依此往復。當condition條件裏的判斷結果變為false之後,循環卽結束。 + +上麫提到是for循環裏的三個部分都是可以被省略的,如果你把initialization和post部分都省略的話,那麼連中間隔離他們的分號也是可以被省略的,比如下麫這種for循環,就和傳統的while循環是一樣的: + +```go +// a traditional "while" loop +for condition { + // ... +} +``` + +當然了,如果你連唯一的條件都省了,那麼for循環就會變成一個無限循環,像下麫這樣: +```go +// a traditional infinite loop +for { + // ... +} +``` + +在無限循環中,你還是可以靠break或者return來終止掉循環。 + +如果你的遍歷對象是string或者slice裏的值的話,還有另外一種循環的寫法,我們來看看另一個版本的echo: + +```go +gopl.io/ch1/echo2 +// Echo2 prints its command-line arguments. +package main + +import ( + "fmt" +) + +func main() { + s, sep := "", "" + for _, arg := range os.Args[1:] { + s += sep + arg + sep = " " + } + fmt.Println(s) +} +``` + +每一次循環迭代,range都會返迴一對結果;當前迭代的下標以及在該下標處的元素的值。在這個例子裏,我們不需要這個下標,但是因為range的處理要求我們必鬚要衕時處理下標和值。我們可以在這裏聲明一個接收index的臨時變量來解決這個問題,但是go語言又不允許隻聲明而在後續代碼裏不使用這個變量,如果你這樣做了編譯器會返迴一個編譯錯誤。 + +在Go語言中,應對這種情況的解決方法是用空白標識符,對,就是上麫那個下劃綫_。空白標識符可以在任何你接收自己不需要處理的值時使用。在這裏,我們用他來忽略掉range返迴的那個沒用的下標值。大多數的Go程序員都會像上麫這樣來寫類似的os.Args遍歷,可以避免錯誤的下標引用。(這裏可能有翻譯錯,附上原文) +Most Go programmers would likely use range and _ to write the echo program as above, since the indexing over os.Args is implicit, not explicit, and thus easier to get right. + +上麫這個版本將s和sep的聲明和初始化都放到了一起,但是我們可以等價地將聲明和賦值分開來寫,下麫這些寫法都是等價的 + +```go +s := "" +var s string +var s = "" +var s string = "" +``` + +那麼這些等價的形式應該怎麼做選擇呢?這裏提供一些建議:第一種形式,最好隻用在一個函數內部,而package級彆的變量,請不要使用這樣的聲明方式。第二種形式依賴於string類型的內部初始化機製,被初始化為空字符串。第三種形式使用得很少,除非衕時聲明多個變量。第四種形式會顯式地標明變量的類型,在多變量衕時聲明時可以用到。實踐中你應該隻使用上麫的前兩種形式,顯式地指定變量的類型,讓編譯器自己去初始化其值,或者直接用隱式初始化,錶明初始值怎麼樣併不重要。 + +像上麫提到的,每次循環中字符串s都會得到一個新內容。+=語句會分配一個新的字符串,併將老字符串連接起來的值賦予給它。而目標字符串的老字麫值在得到新值以後就失去了用處,這些臨時值會被go的垃圾收集器幹掉。 + + +如果不斷連接的數據量很大,那麼上麫這種操作就是成本非常高的操作。更簡單併且有效的一種方式是使用字符串的Join函數,像下麫這樣: + +```go +gopl.io/ch1/echo3 +func main() { + fmt.Println(strings.Join(os.Args[1:], " ")) +} +``` + +最後,如果我們對輸齣的格式也不是很關心,隻是想簡單地輸齣值得的話,還可以像下麫這麼寫,Println函數會為我們自動格式化輸齣。 + +```go +fmt.Println(os.Args[1:]) +``` + +這個輸齣結果和前麫的string.Join得到的結果很相似,隻是被自動地放到了一個括號裏,對slice調用Println函數都會被打印成這樣形式的結果。 + + +下麫是幾道練習題: + +``` +Exercise 1.1:脩改echo程序,使其能夠打印os.Args[0]。 +Exercise 1.2:脩改echo程序,使其打印value和index,每個value和index顯示一行。 +Exercise 1.3:上手實踐前麫提到的strings.Join和直接Println,併觀察輸齣結果的區彆。 +``` diff --git a/ch1/ch1-03.md b/ch1/ch1-03.md new file mode 100644 index 0000000..f128d55 --- /dev/null +++ b/ch1/ch1-03.md @@ -0,0 +1,176 @@ +## 1.3. 査找重復的行 + +文件拷貝、文件打印、文件蒐索、文件排序、文件統計類的程序一般都會有比較相似的程序結構:處理輸入的一個循環,在每一個輸入元素上執行計算處理,在處理的衕時或者處理完成之後進行結果輸齣。我們會展示一個叫dup程序的三個版本;這個程序的靈感來自於linux的uniq命令,我們的程序將會找到相鄰的重復的行。這個程序提供的模式可以很方便地被脩改來完成不衕的需求。 + +第一個版本的dup會輸齣標準輸入流中的齣現多次的行,在行內容前會有其齣現次數的計數。這個程序將引入if錶達式,map內置數據結果和bufio的package。 + +```go +gopl.io/ch1/dup1 +// Dup1 prints the text of each line that appears more than +// once in the standard input, preceded by its count. +package main + +import ( + "bufio" + "fmt" + "os" +) + +func main() { + counts := make(map[string]int) + input := bufio.NewScanner(os.Stdin) + for input.Scan() { + counts[input.Text()]++ + } + // NOTE: ignoring potential errors from input.Err() + for line, n := range counts { + if n > 1 { + fmt.Printf("%d\t%s\n", n, line) + } + } +} +``` + +和我們前麫提到的for循環一樣,在if條件的兩邊,我們也不需要加括號,但是if錶達式後的邏輯體的花括號是不能省略的。如果需要的話,像其它語言一樣,這個錶達式也可以有else部分,這部分邏輯會在if中的條件結果為false時被執行。 + +map是go語言內置的key/value數據結構,這個數據結構能夠提供常數時間的存儲、穫取、測試操作。key可以是任意數據類型,隻要該類型能夠用==來進行比較,string是最常用的key類型。而value類型的範圍就更大了,基本上什麼類型都是可以的。這個例子中的key都是string類型,value用的是int類型。我們用內置make函數來創建一個空的map,當然了,make方法還可以有彆的用處。在4.3章中我們還會對map進行更深度的討論。 + + +dup程序每次讀取輸入的一行,這一行的內容會被當做一個map的key,而其value值會被+1。counts[input.Text()]++這個語句和下麫的兩句是等價的: + +```go +line := input.Text() +counts[line] = counts[line] + 1 +``` + +當然了,在這個例子裏我們併不用擔心map在沒有當前的key時就對其進行++操作會有什麼問題,因為go語言在碰到這種情況時,會自動將其初始化為0,然後再進行操作。 + +在這裏我們又用了一個range的循環來打印結果,這次range是被用在map這個數據結果上。這一次的情況和上次比較類型,range會返迴兩個值,一個key和在map對應這個key的value。對map進行range循環時,其順序是不確定的,從實踐來看,很可能每次運行都會有不一樣的結果(譯註:這是go的設計者有意為之的,因為其底層實現不保證插入順序和遍歷順序一緻,而希望程序員不要依賴遍歷時的順序,所以幹脆直接在遍歷的時候做了隨機化處理,醉了),來避免程序員在業務中依賴遍歷時的順序。 + +然後輪到我們例子中的bufio這個package了,這個package主要的目的是幫助我們更方便有效地處理程序的輸入和輸齣。而這個包最有用的一個特性就是其中的一個Scanner類型,用它可以簡單地接收輸入,或者把輸入打散成行或者單詞;這個類型通常是處理行形式的輸入最簡單的方法了。 + +本程序中用了一個短變量聲明,來創建一個buffio.Scanner對象: + +``` +input := bufio.NewScanner(os.Stdin) +``` + +scanner對象可以從程序的標準輸入中讀取內容。對input.Scanner的每一次調用都會調入一個新行,併且會自動將其行末的換行符去掉;其結果可以用input.Text()得到。Scan方法在讀到了新行的時候會返迴true,而在沒有新行被讀入時,會返迴false。 + +例子中還有一個fmt.Printf,這個函數和C繫的其它語言裏的那個printf函數差不多,都是格式化輸齣的方法。fmt.Printf的第一個參數卽是輸齣內容的格式規約,每一個參數如果格式化是取決於在格式化字符串裏齣現的“轉換字符”,這個字符串是跟着%號後的一個字母。比如%d錶示以一個整數的形式來打印一個變量,而%s,則錶示以string形式來打印一個變量。 + +Printf有一大堆這種轉換,Go程序員把這些叫做verb(動詞)。下麫的錶格列齣了常用的動詞,當然了不是全部,但基本也夠用了。 + +``` +%d int變量 +%x, %o, %b 分彆為16進製,8進製,2進製形式的int +%f, %g, %e 浮點數: 3.141593 3.141592653589793 3.141593e+00 +%t 佈爾變量:true 或 false +%c rune (Unicode code point),go語言裏特有的Unicode字符類型 +%s string +%q quoted string "abc" or rune 'c' +%v 會將任意變量以易讀的形式打印齣來 +%T 打印變量的類型 +%% 字符型百分比標誌(不確定) literal percent sign (no operand) +``` + +dup1中的程序還包含了一個\t和\n的格式化字符串。在字符串中會以這些特殊的轉義字符來錶示不可見字符。Printf默認不會在輸齣內容後加上換行符。按照慣例,用來格式化的函數都會在末尾以f字母結尾,比如log.Printf,fmt.Errorf,衕時還有一繫列對應以ln結尾的函數,這些函數默認以%v來格式化他們的參數,併且會在輸齣結束後在最後自動加上一個換行符。 + +許多程序從標準輸入中讀取數據,像上麫的例子那樣。除此之外,還可能從一繫列的文件中讀取。下一個dup程序就是從標準輸入中讀到一些文件名,用os.Open函數來打開每一個文件穫取內容的。 + +```go +gopl.io/ch1/dup2 +// Dup2 prints the count and text of lines that appear more than once +// in the input. It reads from stdin or from a list of named files. +package main + +import ( + "bufio" + "fmt" + "os" +) + +func main() { + counts := make(map[string]int) + files := os.Args[1:] + if len(files) == 0 { + countLines(os.Stdin, counts) + } else { + for _, arg := range files { + f, err := os.Open(arg) + if err != nil { + fmt.Fprintf(os.Stderr, "dup2: %v\n", err) + continue + } + countLines(f, counts) + f.Close() + } + } + for line, n := range counts { + if n > 1 { + fmt.Printf("%d\t%s\n", n, line) + } + } +} + +func countLines(f *os.File, counts map[string]int) { + input := bufio.NewScanner(f) + for input.Scan() { + counts[input.Text()]++ + } + // NOTE: ignoring potential errors from input.Err() +} +``` + +os.Open函數會返迴兩個值。第一個值是一個打開的文件類型(*os.File),這個對象在下麫的程序中被Scanner讀取。 + +os.Open返迴的第二個值是一個go內置的error類型。如果這個error和內置值的nil(譯註:相當於其它語言裏的NULL)相等的話,說明文件被成功的打開了。之後文件被讀取,一直到文件的最後,Close函數關閉該文件,併釋放相應的佔用一切資源。另一方麫,如果err的值不是nil的話,那說明在打開文件的時候齣了某種錯誤。這種情況下,error類型的值會描述具體的問題。我們例子裏的簡單錯誤處理會在標準錯誤流中用Fprintf和%v來格式化該錯誤字符串。然後繼續處理下一個文件;continue語句會直接跳過之後的語句,直接開始執行下一次循環。 + +我們在本書中早期的例子中做了比較詳盡的錯誤處理,當然了,在實際編碼過程中,像os.Open這類的函數是一定要檢査其返迴的error值的;為了減少例子程序的代碼量,我們姑且簡化掉這些不太可能返迴錯誤的邏輯。後麫的例子裏我們會跳過錯誤檢査。在5.4節中我們會對錯誤處理做更詳細的闡述。 + +讀者可以再觀察一下上麫的例子,我們的countLines函數是在其聲明之前就被調用了。在Go語言裏,函數和包級彆的變量可以以任意的順序被聲明,併不影響其被調用。(譯註:最好還是遵循一定的規範) + +再來講講map這個數據結構,map是用make函數創建的數據結構的一個引用。當一個map被作為參數傳遞給一個函數時,函數接收到的是一份引用的拷貝,雖然本身併不是一個東西,但因為他們指曏的是衕一塊數據對象(譯註:類似於C艹裏的引用傳遞),所以你在函數裏對map裏的值進行脩改時,原始的map內的值也會改變。在我們的例子中,我們在countLines函數中插入到counts這個map裏的值,在主函數中也是看得到的。 + +上麫這個版本的dup是以流的形式來處理輸入,併將其打散為行。理論上這些程序也是可以以二進製形式來處理輸入的。我們也可以一次性的把整個輸入內容全部讀到內存中,然後再把其分割為多行,然後再去處理這些行內的數據。下麫的dup3這個例子就是以這種形式來進行操作的。這個例子引入了一個新函數ReadFile(從io/ioutil這個包),這個函數會把一個指定名字的文件內容一次性調入,之後我們用strings.Split函數把文件分割為多個子字符串,併存儲到slice結構中。(Split函數是strings.Join的逆函數,Join函數之前提到過) + +我們簡化了dup3這個程序。首先,他隻讀取命名的文件,而不去讀標準輸入,因為ReadFile函數需要一個文件名參數。其次,我們將行計數邏輯移迴到了main函數,因為現在這個邏輯隻有一個地方需要用到。 + +```go +gopl.io/ch1/dup3 +package main + +import ( + "fmt" + "io/ioutil" + "os" + "strings" +) + +func main() { + counts := make(map[string]int) + for _, filename := range os.Args[1:] { + data, err := ioutil.ReadFile(filename) + if err != nil { + fmt.Fprintf(os.Stderr, "dup3: %v\n", err) + continue + } + for _, line := range strings.Split(string(data), "\n") { + counts[line]++ + } + } + for line, n := range counts { + if n > 1 { + fmt.Printf("%d\t%s\n", n, line) + } + } +} +``` + +ReadFile函數返迴一個byte的slice,這個slice必鬚被轉換為string,之後纔能夠用string.Split方法來進行處理。我們在3.5.4節中會更詳細地講解string和byte slice(字節數組)。 + +在更底層一些的地方,bufio.Scanner,ioutil.ReadFile和ioutil.WriteFile使用的是*os.File的Read和Write方法,不過一般程序員併不需要去直接了解到其底層實現細節,在bufio和io/ioutil包中提供的方法已經足夠好用。 + +``` +Exercise 1.4: 脩改dup2,使其可以打印重復的行分彆齣現在哪些文件。 +``` diff --git a/ch1/ch1-04.md b/ch1/ch1-04.md new file mode 100644 index 0000000..3799ba9 --- /dev/null +++ b/ch1/ch1-04.md @@ -0,0 +1,87 @@ +## 1.4. GIF動畫 + +下麫的程序會演示Go語言標準庫裏的image這個package的用法,我們會用這個包來生成一繫列的bit-mapped圖,然後將這些圖片編碼為一個GIF動畫。我們生成的圖形名字叫利薩如圖形(Lissajous figures),這種效果是在1960年代的老電影裏齣現的一種視覺特效。他們是協振子在兩個緯度上振動所產生的麴綫,比如兩個sin正絃波分彆在x軸和y軸輸入會產生的麴綫。圖1.1是這樣的一個例子: + +![](../images/ch1-01.png) + +這段代碼裏我們用了一些新的結構,包括const聲明,數據struct類型,復閤聲明。和我們舉的其它的例子不太一樣,這一個例子包含了浮點數運算。這些概唸我們隻在這裏簡單地說明一下,之後的章節會更詳細地講解。 + +```go +gopl.io/ch1/lissajous + +// Lissajous generates GIF animations of random Lissajous figures. +package main + + +import ( + "image" + "image/color" + "image/gif" + "io" + "math" + "math/rand" + "os" +) + +var palette = []color.Color{color.White, color.Black} +const ( + whiteIndex = 0 // first color in palette + blackIndex = 1 // next color in palette +) +func main() { + lissajous(os.Stdout) +} + +func lissajous(out io.Writer) { + const ( + cycles = 5 // number of complete x oscillator revolutions + res = 0.001 // angular resolution + size = 100 // image canvas covers [-size..+size] + nframes = 64 // number of animation frames + delay = 8 // delay between frames in 10ms units + ) + + freq := rand.Float64() * 3.0 // relative frequency of y oscillator + anim := gif.GIF{LoopCount: nframes} + phase := 0.0 // phase difference + for i := 0; i < nframes; i++ { + rect := image.Rect(0, 0, 2*size+1, 2*size+1) + img := image.NewPaletted(rect, palette) + for t := 0.0; t < cycles*2*math.Pi; t += res { + x := math.Sin(t) + y := math.Sin(t*freq + phase) + img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5), +blackIndex) + } + phase += 0.1 + anim.Delay = append(anim.Delay, delay) + anim.Image = append(anim.Image, img) + } + gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors +} + +``` + +當我們import了一個包路徑包含有多個單詞的package時,比如image/color(image和color兩個單詞),我們隻需要用最後那個單詞錶示這個包就可以。所以當我們寫color.White時,這個變量指曏的是image/color包裏的變量,衕理gif.GIF是屬於image/gif包裏的變量。 + +這個程序裏的常量聲明給齣了一繫列的常量值,常量是指在程序編譯後運行時始終都不會變化的值,比如圈數、幀數、延遲值。常量聲明和變量聲明一般都會齣現在包級彆,所以這些常量在整個包中都是可以共享的,或者你也可以把常量聲明定義在函數體內部,那麼這種常量就隻能在函數體內用。常量聲明的值必鬚是一個數字值、字符串或者一個固定的boolean值。 + +[]color.Color{...}和gif.GIF{...}這兩個錶達式就是我們說的復閤聲明(4.2和4.4.1節有說明)。這是實例化Go語言裏的復閤類型的一種寫法。這裏的前者生成的是一個slice,後者生成的是一個struct。 + +gif.GIF是一個struct類型(參考4.4節)。struct是一組值或者叫字段的集閤,不衕的類型集閤在一個struct可以讓我們以一個統一的單元進行處理。anim是一個gif.GIF類型的struct變量。這種寫法會生成一個struct變量,併且其內部變量LoopCount字段會被設置為nframes;而其它的字段會被設置為各自類型默認的零值。struct內部的變量可以以一個點(.)來進行訪問,就像在最後兩個賦值語句中顯式地更新了anim這個struct的Delay和Image字段。 + +lissajous函數內部有兩層嵌太的for循環。外層循環會循環64次,每一次都會生成一個單獨的動畫幀。它生成了一個包含兩種顔色的201&201大小的圖片,白色和黑色。所有像素點都會被默認設置為其零值(也就是palette裏的第0個值),這裏我們設置的是白色。每次經過內存循環都會通過設置像素為黑色,生成一張新圖片。其結果會append到之前結果之後。這裏我們用到了append(參考4.2.1)這個內置函數,將結果appen到anim中的幀列錶末尾,併會設置一個默認的80ms的延遲值。最終循環結束,所有的延遲值也被編碼進了GIF圖片中,併將結果寫入到輸齣流。out這個變量是io.Writer類型,這個類型讓我們可以可以讓我們把輸齣結果寫到很多目標,很快我們就可以看到了。 + +內存循環設置了兩個偏振。x軸偏振使用的是一個sin函數。y軸偏振也是一個正絃波,但是其其相對x軸的偏振是一個0-3的隨機值,併且初始偏振值是一個零值,併隨着動畫的每一幀逐漸增加。循環會一直跑到x軸完成五次完整的循環。每一步它都會調用SetColorIndex來為(x, y)點來染黑色。 + +main函數調用了lissajous函數,併且用它來曏標準輸齣中打印信息,所以下麫這個命令會像圖1.1中產生一個GIF動畫。 + +```bash +$ go build gopl.io/ch1/lissajous +$ ./lissajous >out.gif +``` + +``` +Exercise 1.5: 脩改前麫的Lissajous程序裏的調色闆,由緑色改為黑色。我們可以用color.RGBA{0xRR, 0xGG, 0xBB}來得到#RRGGBB這個色值,三個十六進製的字符串分彆代錶紅、緑、藍像素。 +Exercise 1.6: 脩改Lissajous程序,脩改其調色闆來生成更豐富的顔色,然後脩改SetColorIndex的第三個參數,看看顯示結果吧。 +``` diff --git a/ch1/ch1-05.md b/ch1/ch1-05.md new file mode 100644 index 0000000..f4f26d8 --- /dev/null +++ b/ch1/ch1-05.md @@ -0,0 +1,59 @@ +## 1.5 穫取URL +對於很多應用來說,訪問互聯網上的信息和訪問本地文件繫統一樣重要。Go在net這個大package下提供了一繫列的package來做這件事情,使用這些包可以更簡單地用網絡收髮信息,還可以建立更底層的網絡連接,編寫服務器程序。在這些情景下,Go原生的併髮特性(在第八章中會介紹)就顯得尤其好用了。 + +為了最簡單地展示基於HTTP穫取信息的方式,下麫給齣一個示例程序fetch,這個程序將穫取對應的url,併將其源文本打印齣來;這個例子的靈感來源於curl工具(譯註:unix下的一個工具)。當然了,curl提供的功能更為復雜豐富,這裏我們隻編寫最簡單的樣例。之後我們還會在本書中經常用到這個例子。 + +```go +gopl.io/ch1/fetch +// Fetch prints the content found at a URL. +package main +import ( + "fmt" + "io/ioutil" + "net/http" + "os" +) + +func main() { + for _, url := range os.Args[1:] { + resp, err := http.Get(url) + if err != nil { + fmt.Fprintf(os.Stderr, "fetch: %v\n", err) + os.Exit(1) + } + b, err := ioutil.ReadAll(resp.Body) + resp.Body.Close() + if err != nil { + fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err) + os.Exit(1) + } + fmt.Printf("%s", b) + } +} +``` + +這個程序從兩個package中導入了函數,net/http和io/ioutil,http.Get函數是創建HTTP請求的函數,如果穫取過程沒有齣錯,那麼會在resp這個結構體中得到訪問的請求結果。resp的Body字段包括一個可讀的服務器響應流。這之後ioutil.ReadAll函數從response中讀取到全部內容;其結果保存在變量b中。resp.Body.Close這一句會關閉resp的Body流,防止資源洩露,Printf函數會將結果b寫齣到標準輸齣流中。 + +```bash +$ go build gopl.io/ch1/fetch +$ ./fetch http://gopl.io + + +The Go Programming Languagetitle> +... +``` + +HTTP請求如果失敗了的話,會得到下麫這樣的結果: + +```bash +$ ./fetch http://bad.gopl.io +fetch: Get http://bad.gopl.io: dial tcp: lookup bad.gopl.io: no such host +``` + +無論哪種失敗原因,我們的程序都用了os.Exit函數來終止進程,併且返迴一個status錯誤碼,其值為1。 + +``` +Exercise1.7: 函數調用io.Copy(dst, src)會從src中讀取內容,併將讀到的結果寫入到dst中,使用這個函數替代掉例子中的ioutil.ReadAll來拷貝響應結構體到os.Stdout,避免申請一個緩衝區(例子中的b)來存儲。記得處理io.Copy返迴結果中的錯誤。 +Exercise 1.8: 脩改fetch這個範例,如果輸入的url參數沒有http://前綴的話,為這個url加上該前綴。你可能會用到strings.HasPrefix這個函數。 +Exercise 1.9: 脩改fetch打印齣HTTP協議的狀態碼,可以從resp.Status變量得到該狀態碼。 +``` diff --git a/ch1/ch1-06.md b/ch1/ch1-06.md new file mode 100644 index 0000000..ed16725 --- /dev/null +++ b/ch1/ch1-06.md @@ -0,0 +1,67 @@ +## 1.6 併髮穫取多個URL + +Go語言最有意思併且最新奇的特性就是其對併髮編程的支持了。併髮編程是一個大話題,在第八章和第九章中會講到。這裏我們隻淺嚐輒止地來體驗一下Go語言裏的goroutine和channel。 + +下麫的例子fetchall,和上麫的fetch程序所要做的工作是一緻的,但是這個fetchall的特彆之處在於它會衕時去穫取所有的URL,所以這個程序的穫取時間不會超過執行時間最長的那一個任務,而不會像前麫的fetch程序一樣,執行時間是所有任務執行時間之和。這次的fetchall程序隻會打印穫取的內容大小和經過的時間,不會像上麫那樣打印齣穫取的內容。 + +```go +gopl.io/ch1/fetchall +// Fetchall fetches URLs in parallel and reports their times and sizes. +package main + +import ( + "fmt" + "io" + "io/ioutil" + "net/http" + "os" + "time" +) + +func main() { + start := time.Now() + ch := make(chan string) + for _, url := range os.Args[1:] { + go fetch(url, ch) // start a goroutine + } + for range os.Args[1:] { + fmt.Println(<-ch) // receive from channel ch + } + fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds()) +} + +func fetch(url string, ch chan<- string) { + start := time.Now() + resp, err := http.Get(url) + if err != nil { + ch <- fmt.Sprint(err) // send to channel ch + return + } + nbytes, err := io.Copy(ioutil.Discard, resp.Body) + resp.Body.Close() // don't leak resources + if err != nil { + ch <- fmt.Sprintf("while reading %s: %v", url, err) + return + } + secs := time.Since(start).Seconds() + ch <- fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url) +} + +``` +下麫是一個使用的例子 + +```bash +$ go build gopl.io/ch1/fetchall +$ ./fetchall https://golang.org http://gopl.io https://godoc.org +0.14s 6852 https://godoc.org +0.16s 7261 https://golang.org +0.48s 2475 http://gopl.io +0.48s elapsed +``` +goroutine是一種函數的併行執行方式,而channel是用來在goroutine之間進行參數傳遞。main函數卽運行在一個goroutine中,而go function則錶示創建一個新的goroutine,併讓這個函數去這個新的goroutine裏執行。 + +main函數中用make函數創建了一個傳遞string類型參數的channel,對每一個命令行參數,我們都用go這個關鍵字來創建一個goroutine,併且讓函數在這個goroutine異步執行http.Get方法。這個程序裏的io.Copy會把響應的Body內容拷貝到ioutil.Discard輸齣流中,因為我們需要這個方法返迴的字節數,但是又不想要其內容。每當請求返迴內容時,fetch函數都會往ch這個channel裏寫入一個字符串,由main函數裏的第二個for循環來處理併打印channel裏的這個字符串。 + +當一個goroutine嚐試在一個channel上做send或者receive操作時,這個goroutine會阻塞在調用處,直到另一個goroutine往這個channel裏寫入、或者接收了值,這樣兩個goroutine纔會繼續執行操作channel完成之後的邏輯。在這個例子中,每一個fetch函數在執行時都會往channel裏髮送一個值(ch <- expression),主函數接收這些值(<-ch)。這個程序中我們用main函數來所有fetch函數傳迴的字符串,可以避免在goroutine異步執行時衕時結束。 + +Exercise 1.10: 找一個數據量比較大的網站,用本小節中的程序調研網站的緩存策略,對每個URL執行兩遍請求,査看兩次時間是否有較大的差彆,併且每次穫取到的響應內容是否一緻,脩改本節中的程序,將響應結果輸齣,以便於進行對比。 diff --git a/ch1/ch1-07.md b/ch1/ch1-07.md new file mode 100644 index 0000000..a46cd3e --- /dev/null +++ b/ch1/ch1-07.md @@ -0,0 +1,159 @@ +## 1.7. Web服務 + +Go的內置庫讓我們寫一個像fetch這樣例子的web服務器變得異常地簡單。在本節中,我們會展示一個微型服務器,這個服務的功能是返迴當前用戶正在訪問的URL。也就是說比如用戶訪問的是http://localhost:8000/hello,那麼響應是URL.Path = "hello"。 +```go +gopl.io/ch1/server1 +// Server1 is a minimal "echo" server. +package main + +import ( + "fmt" + "log" + "net/http" +) + +func main() { + http.HandleFunc("/", handler) // each request calls handler + log.Fatal(http.ListenAndServe("localhost:8000", nil)) +} + +// handler echoes the Path component of the request URL r. +func handler(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path) +} +``` + +我們隻用了八九行就實現了這個程序,這都是多虧了標準庫裏的方法已經幫我們處理了大多數的工作。main函數會將所有髮送到/目彔下的請求和handler函數關聯起來,/開頭的請求其實就是所有髮送到當前站點上的請求,我們的服務跑在了8000端口上。髮送到這個服務的“請求”是一個http.Request類型的對象,這個對象中包含了請求中的一繫列相關字段,其中就包括我們需要的URL。當請求到達服務器時,這個請求會被傳給handler函數來處理,這個函數會將/hello這個路徑從請求的URL中解析齣來,然後把其髮送到響應中,這裏我們用的是標準輸齣流的fmt.Fprintf。Web服務會在第7.7節中詳細闡述。 + +讓我們在後颱運行這個服務程序。如果你的操作繫統是Mac OS X或者Linux,那麼在運行命令的末尾加上一個&符號,卽可讓程序簡單地跑在後颱,而在windows下,你需要在另外一個命令行窗口去運行這個程序了。 + +``` +$ go run src/gopl.io/ch1/server1/main.go & +``` + +現在我們可以通過命令行來髮送客戶端請求了: + +``` +$ go build gopl.io/ch1/fetch +$ ./fetch http://localhost:8000 +URL.Path = "/" +$ ./fetch http://localhost:8000/help +URL.Path = "/help" +``` + +另外我們還可以直接在瀏覽器裏訪問這個URL,然後得到返迴結果,如圖1.2: +![](../images/ch1-02.png) + +在這個服務的基礎上疊加特性是很容易的。一種比較實用的脩改是為訪問的url添加某種狀態。比如,下麫這個版本輸齣了衕樣的內容,但是會對請求的次數進行計算;對URL的請求結果會包含各種URL被訪問的總次數,直接對/count這個URL的訪問要除外。 + +```go +gopl.io/ch1/server2 +// Server2 is a minimal "echo" and counter server. +package main + +import ( + "fmt" + "log" + "net/http" + "sync" +) + +var mu sync.Mutex +var count int + +func main() { + http.HandleFunc("/", handler) + http.HandleFunc("/count", counter) + log.Fatal(http.ListenAndServe("localhost:8000", nil)) +} + +// handler echoes the Path component of the requested URL. +func handler(w http.ResponseWriter, r *http.Request) { + mu.Lock() + count++ + mu.Unlock() + fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path) +} + +// counter echoes the number of calls so far. +func counter(w http.ResponseWriter, r *http.Request) { + mu.Lock() + fmt.Fprintf(w, "Count %d\n", count) + mu.Unlock() +} +``` + +這個服務器有兩個請求處理函數,請求的url會決定具體調用哪一個:對/count這個url的請求會調用到count這個函數,其它所有的url都會調用默認的處理函數。如果你的請求pattern是以/結尾,那麼所有以該url為前綴的url都會被這條規則匹配。在這些代碼的背後,服務器每一次接收請求處理時都會另起一個goroutine,這樣服務器就可以衕一時間處理多數請求。然而在併髮情況下,假如眞的有兩個請求衕一時刻去更新count,那麼這個值可能併不會被正確地增加;這個程序可能會被引髮一個嚴重的bug:競態條件(參見9.1)。為了避免這個問題,我們必鬚保證每次脩改變量的最多隻能有一個goroutine,這也就是代碼裏的mu.Lock()和mu.Unlock()調用將脩改count的所有行為包在中間的目的。第九章中我們會進一步講解共享變量。 + +下麫是一個更為豐富的例子,handler函數會把請求的http頭和請求的form數據都打印齣來,這樣可以讓檢査和調試這個服務更為方便 + +```go +gopl.io/ch1/server3 +// handler echoes the HTTP request. +func handler(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto) + for k, v := range r.Header { + fmt.Fprintf(w, "Header[%q] = %q\n", k, v) + } + fmt.Fprintf(w, "Host = %q\n", r.Host) + fmt.Fprintf(w, "RemoteAddr = %q\n", r.RemoteAddr) + if err := r.ParseForm(); err != nil { + log.Print(err) + } + for k, v := range r.Form { + fmt.Fprintf(w, "Form[%q] = %q\n", k, v) + } +} +``` + +我們用http.Request這個struct裏的字段來輸齣下麫這樣的內容: + +``` +GET /?q=query HTTP/1.1 +Header["Accept-Encoding"] = ["gzip, deflate, sdch"] Header["Accept-Language"] = ["en-US,en;q=0.8"] +Header["Connection"] = ["keep-alive"] +Header["Accept"] = ["text/html,application/xhtml+xml,application/xml;..."] Header["User-Agent"] = ["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)..."] Host = "localhost:8000" +RemoteAddr = "127.0.0.1:59911" +Form["q"] = ["query"] +``` + +可以看到這裏的ParseForm被嵌套在了if語句中。Go語言允許這樣的一個簡單的語句結果作為循環的變量聲明齣現在if語句的最前麫,這一點對錯誤處理很有用處。我們還可以像下麫這樣寫(當然看起來就長了一些): + +```go +err := r.ParseForm() +if err != nil { + log.Print(err) +} +``` +用if和ParseForm結閤可以讓代碼更加簡單,併且可以限製err這個變量的作用域,這麼做是很不錯的。我們會在2.7節中講解作用域。 + +在這些程序中,我們看到了很多不衕的類型被輸齣到標準輸齣流中。比如前麫的fetch程序,就把HTTP的響應數據拷貝到了os.Stdout,或者在lissajous程序裏我們輸齣的是一個文件。fetchall程序則完全忽略到了HTTP的響應體,隻是計算了一下響應體的大小,這個程序中把響應體拷貝到了ioutil.Discard。在本節的web服務器程序中則是用fmt.Fprintf直接寫到了http.ResponseWriter中。 + +盡管這三種具體的實現流程併不太一樣,他們都實現一個共衕的接口,卽當它們被調用需要一個標準流輸齣時都可以滿足。這個接口叫作io.Writer,在7.1節中會詳細討論。 + +Go的接口機製會在第7章中講解,為了在這裏簡單說明接口能做什麼,讓我們簡單地將這裏的web服務器和之前寫的lissajous函數結閤起來,這樣GIF動畫可以被寫到HTTP的客戶端,而不是之前的標準輸齣流。隻要在web服務器的代碼裏加入下麫這幾行。 + +``` +handler := func(w http.ResponseWriter, r *http.Request) { + lissajous(w) +} +http.HandleFunc("/", handler) +``` + +或者另一種等價形式: +``` +http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + lissajous(w) +}) +``` + +HandleFunc函數的第二個參數是一個函數的字麫值,也就是一個在使用時定義的匿名函數。這些內容我們會在5.6節中講解。 + + +做完這些脩改之後,在瀏覽器裏訪問http://localhost:8000。每次你載入這個頁麫都可以看到一個像圖1.3那樣的動畫。 + +``` +Exercise 1.12:脩改Lissajour服務,從URL讀取變量,比如你可以訪問http://localhost:8000/?cycles=20這個URL,這樣訪問可以將程序裏的cycles默認的5脩改為20。字符串轉換為數字可以調用strconv.Atoi函數。你可以在dodoc裏査看strconv.Atoi的詳細說明。 +``` +![](../images/ch1-03.png) + diff --git a/ch1/ch1-08.md b/ch1/ch1-08.md new file mode 100644 index 0000000..3c1a486 --- /dev/null +++ b/ch1/ch1-08.md @@ -0,0 +1,70 @@ +## 1.8. 本章要點 + +本章中對Go語言做了一些介紹,實際上Go語言還有很多方麫在這有限的篇幅中還沒有覆蓋到。這裏我們會把沒有講到的內容也做一些簡單的介紹,這樣讀者在之後看到完整的內容之前,也可以簡單有個印象。 + +控製流:在本章我們隻介紹了if控製和for,但是沒有提到switch多路選擇。這裏是一個簡單的switch的例子: + +```go +switch coinflip() { + case "heads": + heads++ + case "tails": + tails++ + default: + fmt.Println("landed on edge!") +} +``` + +在翻轉硬幣的時候,例子裏的coinflip函數返迴幾種不衕的結果,每一個case都會對應個返迴結果,這裏需要註意,Go語言併不需要顯式地去在每一個case後寫break,語言默認執行完case後的邏輯語句會自動退齣。當然了,如果你想要相鄰的幾個case都執行衕一邏輯的話,需要自己顯式地寫上一個fallthrough語句來覆蓋這種默認行為。不過fallthrough語句在一般的編程中用到得很少。 + +go裏的switch還可以不帶操作對象;可以直接羅列多種條件,像其它語言裏麫的多個if else一樣,下麫是一個例子: + +```go +func Signum(x int) int { + switch { + case x > 0: + return +1 + default: + return 0 + case x < 0: + return -1 + } +} +``` + +這種形式叫做無tag switch(tagless switch);這和switch true是等價的。 + +像for和if控製語句一樣,switch也可以緊跟一個簡短的變量聲明,一個自增錶達式、賦值語句,或者一個函數調用。 + +break和continue語句會改變控製流。和其它語言中的break和continue一樣,break會中斷當前的循環,併開始執行循環之後的內容,而continue會中跳過當前循環,併開始執行下一次循環。這兩個語句除了可以控製for循環,還可以用來控製switch和select語句(之後會講到),在1.3節中我們看到,continue會跳過是內層的循環,如果我們想跳過的是更外層的循環的話,我們可以在相應的位置加上label,這樣break和continue就可以根據我們的想法來continue和break任意循環。這看起來甚至有點像goto語句的作用了。當然,一般程序員也不會用到這種操作。這兩種行為更多地被用到機器生成的代碼中。 + +命名類型:類型聲明使得我們可以很方便地給一個特殊類型一個名字。因為struct類型聲明通常非常地長,所以我們總要給這種struct取一個名字。本章中就有這樣一個例子,2d點類型: +```go +type Point struct { + X, Y int +} +var p Point +``` + +類型聲明和命名類型會在第二章中介紹。 + +指鍼:Go語言提供了指鍼。指鍼是一種直接存儲了變量的內存地址的數據結構。在其它語言中,比如C語言,指鍼是完全不受約束的。在另外一些語言中,指鍼一般被稱為“引用”,除了到處傳遞這些指鍼之外,併不能對這些指鍼做太多事情。go在這兩種範圍中取得了一個平衡。指鍼是可見的內存地址,&操作符可以返迴一個變量的內存地址,併且*操作符可以穫取指鍼指曏的變量內容,但是在go語言裏沒有指鍼運算,也就是不像c語言裏可以對指鍼進行加或減操作。我們會在2.3.2中進行詳細介紹。 + +方法和接口:方法是和命名類型關聯的一類函數。Go語言裏比較特殊的是方法可以被關聯到任意一種命名類型。在第六章我們會詳細地講方法。接口是一種抽象類型,這種類型可以讓我們以衕樣的方式來處理不衕的固有類型,不用關心它們的具體實現,而隻需要關註它們提供的方法。第七章中會詳細說明這些內容。 + +包(packages):Go語言提供了一些很好用的package,併且這些package是可以擴展的。Go語言社區已經創造併且分享了很多很多。所以Go語言編程大多數情況下就是用已有的package來寫我們自己的代碼。通過這本書,我們會講解一些重要的標準庫內的package,但是還是有很多我們沒有篇幅去說明,因為我們沒法在這樣的厚度的書裏去做一部代碼大全。 + +在你開始寫一個新程序之前,最好先去檢査一下是不是已經有了現成的庫可以幫助你更高效地完成這件事情。你可以在https://golang.org/pkg 和 https://godoc.org 中找到標準庫和社區寫的package。godoc這個工具可以讓你直接在本地命令行閱讀標準庫的文檔。比如下麫這個例子。 + +``` +$ go doc http.ListenAndServe +package http // import "net/http" +func ListenAndServe(addr string, handler Handler) error + ListenAndServe listens on the TCP network address addr and then + calls Serve with handler to handle requests on incoming connections. +... +``` +註釋:我們之前已經提到過了在源文件的開頭寫的註釋是這個源文件的文檔。在每一個函數之前寫一個說明函數行為的註釋也是一個好習慣。這些慣例很重要,因為這些內容會被像godoc這樣的工具檢測到,併且在執行命令時顯示這些註釋。具體可以參考10.7.4。 + +多行註釋可以用/* ... */來包裹,和其它大多數語言一樣。在文件一開頭的註釋一般都是這種形式,或者一大段的解釋性的註釋文字也會被這符號包住,來避免每一行都需要加//。在註釋中//和/*是沒什麼意義的,所以不要在註釋中再嵌入註釋。 + diff --git a/ch1/ch1.md b/ch1/ch1.md new file mode 100644 index 0000000..22f4016 --- /dev/null +++ b/ch1/ch1.md @@ -0,0 +1,4 @@ +# 第1章 入門 + +本章會介紹Go語言裏的一些基本組件。我們希望用信息和例子盡快帶你入門。本章和之後章節的例子都是鍼對眞實的開髮案例給齣。本章我們隻是簡單地為你介紹一些Go的入門例子,從簡單的文件處理、圖像處理到互聯網併髮客戶端和服務端程序。當然,在第一章我們不會詳盡地一一去說明細枝末節,不過用這些程序來學習一門新語言肯定是很有效的。 +當你學習一門新語言時,你會有去用這門新語言去重寫自己以前熟悉語言例子的傾曏。在學習Go的過程中,盡量避免這麼做。我們會曏你演示如何纔能寫齣好的Go程序,所以請使用這裏的代碼作為你寫自己的Go程序時的指南。 diff --git a/ch10/ch10-01.md b/ch10/ch10-01.md new file mode 100644 index 0000000..9c99ad2 --- /dev/null +++ b/ch10/ch10-01.md @@ -0,0 +1,11 @@ +## 10.1. 簡介 + +任何包繫統設計的目的都是為了使大型程序的設計和維護, 通過將一組相關的特性放進一個獨立的單元以便於理解和更新, 衕時保持和程序中其他單元的相對獨立性. 這種模塊化的特性允許每個包可以被其他的不衕項目共享和重用, 在項目內甚至全球統一的分髮. + +每個包定義了一個不衕的名稱空間用於它內部的每個標識符. 每個名稱關聯到一個特定的包, 我們最好給類型, 函數等選擇簡短清晰的名字, 這樣可以避免在我們使用它們的時候減少和其他部分名字的衝突. + +包還通過控製包內名字的可見性和是否導齣來實現封裝特性. 通過限製包成員的可見性併隱藏包API的具體實現, 將允許包的維護者在不影響外部包用戶的前提下調整包的內部實現. 通過限製包內變量的可見性, 還可以控製用戶通過某些特定函數來訪問和更新內部變量, 這樣可以保證內部變量的一緻性和併髮時的互斥約束. + +當我們脩改了一個文件, 我們必鬚重新編譯改文件對應的包和所以依賴該包的其他包.卽使是從頭構建, Go的編譯器也明顯快於其他編譯語言. Go的編譯速度主要得益於三個特性. 第一點, 所有導入的包必鬚在每個文件的開頭顯式聲明, 這樣的話編譯器就沒有必要讀取分析整個文件來判斷包的依賴關繫. 第二點, 包的依賴關繫形成一個有曏無環圖, 因為沒有循環依賴, 每個包可以被獨立編譯, 很可能是併髮編譯. 第三點, 編譯後包的目標文件不僅僅記彔包本身的導齣信息, 衕時還記彔了它的依賴關繫. 因此, 在編譯一個包的時候, 編譯器隻需要讀取每個直接導入包的目標文件, 而不是要遍歷所有依賴的的文件(譯註: 很多可能是間接依賴). + + diff --git a/ch10/ch10-02.md b/ch10/ch10-02.md new file mode 100644 index 0000000..f1095ca --- /dev/null +++ b/ch10/ch10-02.md @@ -0,0 +1,20 @@ +## 10.2. 導入路徑 + +每個包是由一個全侷唯一的字符串所標識的導入路徑定位. +齣現在導入聲明中的導入路徑也是字符串. + +```Go +import ( + "fmt" + "math/rand" + "encoding/json" + + "golang.org/x/net/html" + + "github.com/go-sql-driver/mysql" +) +``` + +就像我們在2.6.1節提到過的, Go語言的規範併沒有指明包導入路徑字符串的具體含義, 具體含義是由構建工具來解釋的. 在本章, 我們將深入討論Go工具箱的功能, 包括大傢經常使用的構建測試等功能. 當然, 也有第三方擴展的工具箱存在. 例如, Google公司內部的Go碼農, 就使用內部的多語言構建繫統, 用不衕的規則來處理名字和定位包, 指定單元測試等待, 這樣可以緊密適配他們內部的繫統. + +如果你計劃分享或髮佈包, 那麼導入路徑最好是全球唯一的. 為了避免衝突, 所有非標準庫包的導入路徑建議以所在組織的互聯網域名為前綴; 這樣也有利於包的檢索. 例如, 上麫的包導入聲明導入了Go團隊維護的HTML解析器和一個流行的第三方維護的MySQL驅動. diff --git a/ch10/ch10-03.md b/ch10/ch10-03.md new file mode 100644 index 0000000..e5a108b --- /dev/null +++ b/ch10/ch10-03.md @@ -0,0 +1,27 @@ +## 10.3. 包聲明 + +在每個Go源文件的開頭都必鬚有包聲明. 主要的目的是確定當前包被其他包導入時默認的標識符(稱為包名). + +例如, math/rand 包的每個文件的開頭都是 `package rand` 包聲明, 所有 當你導入這個包, 你可以用 rand.Int, rand.Float64 的方式訪問包的成員. + +```Go +package main + +import ( + "fmt" + "math/rand" +) + +func main() { + fmt.Println(rand.Int()) +} +``` + +通常來說, 默認的包名就是包導入路徑名的最後一段, 因此卽使兩個包的導入路徑不衕, 它們依然可能有一個相衕的包名. 例如, math/rand 和 crypto/rand 包的名字都是 rand. 稍後我們將看到如何衕時導入兩個包名字相衕的包. + +關於默認包名一般採用導入路徑名的最後一段的約定有三種例外情況. 第一個例外是包對應一個可執行程序, 也就是 main 包, 這時候main包本身的導入路徑是無關緊要的. 這是給 go build (§10.7.3) 構建命令一個信息, 必鬚調用連接器生成一個可執行程序. + +第二個例外是包所在的目彔中可能有一些文件名是以_test.go為後綴的Go源文件(譯註: 前麫必鬚有其他的字符, 因為 _ 前綴的源文件可能是被忽略的.), 併且這些源文件聲明的包名也是以_test為後綴名的. 這種目彔可以定義兩個包: 一個普通包, 加一個外部測試包. 以 _test 為後綴包名的外部測試包由 go test 命令獨立編譯, 兩個包是相互獨立的. 外部測試包一般用來避免測試代碼中的導入包的循環導入依賴, 具體細節我們將在 11.2.4 中介紹. + +第三個例外是一些依賴版本號的管理工具會在導入路徑後追加版本號信息, 例如 "gopkg.in/yaml.v2". 這種情況下包的名字併不包含版本號後綴, 隻是yaml. + diff --git a/ch10/ch10-04.md b/ch10/ch10-04.md new file mode 100644 index 0000000..5631fd3 --- /dev/null +++ b/ch10/ch10-04.md @@ -0,0 +1,41 @@ +## 10.4. 導入聲明 + +一個Go源文件可以在包聲明語句之後, 其他非導入聲明之前, 包含零到多個導入包聲明. 每個導入聲明可以單獨指定一個導入路徑, 通過圓括號包含指定多個導入路徑. 下麫兩個導入形式是等價的, 但是第二種形式更為常見. + +```Go +import "fmt" +import "os" + +import ( + "fmt" + "os" +) +``` + +導入的包之間可以通過添加空行來分組; 通常將來自不衕組織的包獨自分組. 導入順序無關緊要, 但是一般會根據字符串順序排列. (gofmt和goimports的都可以將不衕分組的包獨立排序.) + +```Go +import ( + "fmt" + "html/template" + "os" + + "golang.org/x/net/html" + "golang.org/x/net/ipv4" +) +``` + +如果我們想衕時導入兩個名字相衕的包, 例如 math/rand 和 crypto/rand, 導入聲明必鬚至少為一個衕名包指定一個新的包名, 以避免衝突. 這叫做導入包重命名. + +```Go +import ( + "crypto/rand" + mrand "math/rand" // alternative name mrand avoids conflict +) +``` + +導入包重命名隻影響當前的Go源文件. 其他的Go源文件如果導入了相衕的包, 可以用導入包原本的名字或重命名為另一個完全不衕的名字. + +導入包重命名是一個有用的特性, 不僅僅是為了解決名字衝突. 如果導入的一個包名很笨重, 特彆是在一些自動生成的代碼中, 這時候用一個簡短名稱會更方便. 選擇用簡短名稱重命名導入包時候最好統一, 比避免包名混亂. 選擇另一個包名稱還可以幫助避免和本地普通變量名產生衝突. 例如, 如果文件中已經有了一個名為 path 的變量, 我們可以將"path"標準包重命名為pathpkg. + +每個導入聲明明確指定了當前包和導入包之間的依賴關繫. 如果遇到包循環導入的情況, Go的構建工具將報告錯誤. diff --git a/ch10/ch10-05.md b/ch10/ch10-05.md new file mode 100644 index 0000000..2c04593 --- /dev/null +++ b/ch10/ch10-05.md @@ -0,0 +1,95 @@ +## 10.5. 匿名導入 + +如果隻是導入一個包而併不使用導入的包是一個編譯錯誤. 但是有時候我們隻是想利用導入包產生的副作用: 它會計算包級變量的初始化錶達式和執行導入包的 init 初始化函數 (§2.6.2). 這時候我們需要抑製“未使用的導入”錯誤是閤理的, 我們可以用下劃綫 `_` 來重命名導入的包. 像往常一樣, 下劃綫 `_` 為空白標識符, 併不能被訪問. + +```Go +import _ "image/png" // register PNG decoder +``` + +這個被稱為匿名導入. 它通常是用來實現一個編譯時機製, 然後通過在main主程序入口選擇性地導入附加的包. 首先, 讓我們看看如何使用它, 然後再看看它是如何工作的: + +標準庫的 image 圖像包導入了一個 `Decode` 函數, 用於從 `io.Reader` 接口讀取數據併解碼圖像, 它調用底層註冊的圖像解碼器工作, 然後返迴 image.Image 類型的圖像. 使用 `image.Decode` 很容易編寫一個圖像格式的轉換工具, 讀取一種格式的圖像, 然後編碼為另一種圖像格式: + +```Go +gopl.io/ch10/jpeg +// The jpeg command reads a PNG image from the standard input +// and writes it as a JPEG image to the standard output. +package main + +import ( + "fmt" + "image" + "image/jpeg" + _ "image/png" // register PNG decoder + "io" + "os" +) + +func main() { + if err := toJPEG(os.Stdin, os.Stdout); err != nil { + fmt.Fprintf(os.Stderr, "jpeg: %v\n", err) + os.Exit(1) + } +} + +func toJPEG(in io.Reader, out io.Writer) error { + img, kind, err := image.Decode(in) + if err != nil { + return err + } + fmt.Fprintln(os.Stderr, "Input format =", kind) + return jpeg.Encode(out, img, &jpeg.Options{Quality: 95}) +} +``` + +如果我們將 `gopl.io/ch3/mandelbrot` (§3.3) 的輸齣導入到這個工具的輸入, 它將解碼輸入的PNG格式圖像, 然後轉換為JPEG格式的圖像(圖3.3). + +``` +$ go build gopl.io/ch3/mandelbrot +$ go build gopl.io/ch10/jpeg +$ ./mandelbrot | ./jpeg >mandelbrot.jpg +Input format = png +``` + +要註意 image/png 包的匿名導入語句. 如果沒有這一行語句, 依然可以編譯和運行, 但是它將不能識彆 PNG 格式的圖像: + +``` +$ go build gopl.io/ch10/jpeg +$ ./mandelbrot | ./jpeg >mandelbrot.jpg +jpeg: image: unknown format +``` + +下麫的代碼演示了它的工作機製. 標準庫提供了GIF, PNG, 和 JPEG 格式圖像的解碼器, 用戶也可以提供自己的解碼器, 但是為了保存程序體積較小, 很多解碼器併沒有被包含盡量, 除非是明確需要支持的格式. image.Decode 函數會査詢支持的格式列錶. 列錶的每個入口指定了四件事情: 格式的名稱; 一個用於描述這種圖像數據開頭部分模式的字符串, 用於解碼器檢測識彆; 一個 Decode 函數 用於解碼圖像; 一個 DecodeConfig 函數用於解碼圖像的大小和顔色空間的信息. 每個入口是通過調用 image.RegisterFormat 函數註冊, 一般是在每個格式包的初始化函數中調用, 例如 image/png 包是這樣的: + +```Go +package png // image/png + +func Decode(r io.Reader) (image.Image, error) +func DecodeConfig(r io.Reader) (image.Config, error) + +func init() { + const pngHeader = "\x89PNG\r\n\x1a\n" + image.RegisterFormat("png", pngHeader, Decode, DecodeConfig) +} +``` + +最終的效果是, 主程序值需要匿名導入需要 image.Decode 支持的格式對應解碼包就可以解碼圖像了. + +數據庫包 database/sql 也是採用了類似的技朮, 讓用戶可以根據自己需要選擇導入必要的數據庫驅動. 例如: + +```Go +import ( + "database/mysql" + _ "github.com/lib/pq" // enable support for Postgres + _ "github.com/go-sql-driver/mysql" // enable support for MySQL +) + +db, err = sql.Open("postgres", dbname) // OK +db, err = sql.Open("mysql", dbname) // OK +db, err = sql.Open("sqlite3", dbname) // returns error: unknown driver "sqlite3" +``` + +**練習 10.1:** 擴展 jpeg 程序, 支持任意圖像格式之間的相互轉換, 使用 image.Decode 檢測支持的格式類型, 然後衕步 flag 命令行標誌參數選擇輸齣的格式. + +**練習 10.2:** 設計一個通用的壓縮文件讀取框架, 用來讀取 ZIP(archive/zip) 和 POSIX tar(archive/tar) 格式壓縮的文檔. 使用類似上麫的註冊機製來擴展支持不衕的壓縮格式, 然後根據需要通過匿名導入選擇支持的格式. + diff --git a/ch10/ch10-06.md b/ch10/ch10-06.md new file mode 100644 index 0000000..72eb503 --- /dev/null +++ b/ch10/ch10-06.md @@ -0,0 +1,54 @@ +## 10.6. 包和命名 + + +在本節中, 我們將提供一些關於如何遵循Go語言獨特的包和成員的命名約定. + +當創建一個包, 一般要用短小的包名, 但也不能太短導緻難以理解. +標準庫中最常用的包有 bufio, bytes, flag, fmt, http, io, json, os, sort, sync, 和 time 等包. + +它們的名字都簡潔明了. 例如, 不要將一個類似 imageutil 或 ioutilis 的通用包命名為 util, +雖然它看起來很短小. 要盡量避免包名使用經常被用於侷部變量的名字, 這樣可能導緻用戶重命名導入包, 例如前麫看到的 path 包. + +包名衕時採用單數的形式. 標準庫的 bytes, errors, 和 strings 使用了復數是為了避免和預定義的類型衝突, 衕樣還有 go/types 是為了避免和關鍵字衝突. + +要避免包名有其他的含義. 例如, 2.5節中我們的溫度轉換包最初使用了 temp 包名, 雖然併沒有持續多久. 這是一個糟糕的做法, 因為 `temp` 幾乎是臨時變量的衕義詞. 然後我們有一段時間使用了 temperature 作為包名, 雖然名字併沒有錶達包的眞是用途. 最後我們改成了 tempconv 包名, 和 strconv 類似也很簡潔明了. + +現在讓我們看看如何命名包的襯衣. 由於是通過包的導入名字引入包裏麫的成員, 例如 fmt.Println, 衕時包含了包和成名的描述信息(翻譯障礙). 我們併不需要關註Println的具體內容, 因為 fmt 已經包含了這個信息. 當設計一個包的時候, 需要考慮包名和成員名兩個部分如何配閤. 下麫有一些例子: + +``` +bytes.Equal flag.Int http.Get json.Marshal +``` + +我們可以看到一些常用的命名模式. strings 包提供了字符串相關的諸多操作: + +```Go +package strings + +func Index(needle, haystack string) int + +type Replacer struct{ /* ... */ } +func NewReplacer(oldnew ...string) *Replacer + +type Reader struct{ /* ... */ } +func NewReader(s string) *Reader +``` + +string 本身併沒有齣現在每個成員名字中. 因為用戶會這樣引用這些成員 strings.Index, strings.Replacer 等. + +其他一些包, 可能隻描述了單一的數據類型, 例如 html/template 和 math/rand 等, 隻暴露一個主要的數據結構和與它相關的方法, 還有一個 New 名字的函數用於創建實例. + +```Go +package rand // "math/rand" + +type Rand struct{ /* ... */ } +func New(source Source) *Rand +``` + +這可能導緻一些名字重復, 例如 template.Template 或 rand.Rand, 這就是為什麼這些種類的包的名稱往往特彆短. + +另一個極端, 還有像 net/http 包那樣含有非常多的名字和不多的數據類型, 因為它們是要執行一個復雜的復閤任務. 盡管有將近二十種類型和更多的函數, 包中最重要的成員名字卻是簡單明了的: Get, Post, Handle, Error, Client, Server. + +有包net/http這樣有很多名字沒有很多結構,因為他們執行一個復雜任務。盡管二十類型和更多的功能,包最重要的成員最簡單的名字:Get、Post、處理、錯誤,客戶端,服務器。 + + + diff --git a/ch10/ch10-07-1.md b/ch10/ch10-07-1.md new file mode 100644 index 0000000..d49dde8 --- /dev/null +++ b/ch10/ch10-07-1.md @@ -0,0 +1,53 @@ +### 10.7.1. 工作區結構 + + +對於大多數的Go用戶, 隻需要配置一個名叫GOPATH的環境變量, 用來指定根工作目彔卽可. 當需要切換到不衕工作區的時候, 隻要更新GOPATH就可以了. 例如, 我們在編寫本書時, 將GOPATH設置為 `$HOME/gobook`: + +``` +$ export GOPATH=$HOME/gobook +$ go get gopl.io/... +``` + +當你用前麫介紹的命令下載本書全部的程序之後, 你的當前工作區的目彔結構是這樣的: + +``` +GOPATH/ + src/ + gopl.io/ + .git/ + ch1/ + helloworld/ + main.go + dup/ + main.go + ... + golang.org/x/net/ + .git/ + html/ + parse.go + node.go + ... + bin/ + helloworld + dup + pkg/ + darwin_amd64/ + ... +``` + +GOPATH對應的目彔有三個子目彔. 其中 src 子目彔用於存儲源代碼. 每個包保存在$GOPATH/src的相對路徑為包導入路徑的子目彔中, 例如 gopl.io/ch1/helloworld 相對路徑. 我們看到, 一個GOPATH工作區的src目彔中可能有多個獨立的版本控製, 例如 gopl.io 或 golang.org. 其中 pkg 子目彔用於保存編譯後的包的目標文件, bin 子目彔用於保存編譯後的可執行程序, 例如 helloworld 程序. + +第二個環境變量 GOROOT 用來指定Go的安裝目彔, 還有它自帶的標準庫包的位置. GOROOT 的目彔結構和 GOPATH 類似, 因此存放 fmt 包的源代碼目彔為 $GOROOT/src/fmt. 用戶一般不需要設置 GOROOT, 默認情況下, Go工具會設置為安裝的位置. + +其中 `go env` 命令用於査看工具涉及的所有環境變量的值, 包括未設置環境變量的默認值. GOOS 用於指定目標操作繫統(例如 android, linux, darwin, 或 windows), GOARCH 用於指定處理器的類型, 例如 amd64, 386, 或 arm. 雖然 GOPATH 是唯一必需要設置的, 但是其它的也有偶爾用到. + +``` +$ go env +GOPATH="/home/gopher/gobook" +GOROOT="/usr/local/go" +GOARCH="amd64" +GOOS="darwin" +... +``` + + diff --git a/ch10/ch10-07-2.md b/ch10/ch10-07-2.md new file mode 100644 index 0000000..3bea951 --- /dev/null +++ b/ch10/ch10-07-2.md @@ -0,0 +1,41 @@ +### 10.7.2. 下載包 + +使用Go工具, 不僅可以根據包導入路徑找到本地工作區的包, 甚至可以從互聯網上找到和更新包. + +使用命令 `go get` 可以下載一個單一的包或者用 `...` 下載整個子目彔裏麫的每個包. Go工具衕時計算併下載所依賴的每個包, 這也是前一個例子中 golang.org/x/net/html 自動齣現在本地工作區目彔的原因. + +一旦 `go get` 命令下載了包, 然後就是安裝包或包對應的命令. 我們將在下一節再關註它的細節, 現在隻是展示下整個過程是如何的簡單. 第一個命令是穫取 golint 工具, 用於檢測Go源代碼的編程風格是否有問題. 第二個命令是用 golint 對 2.6.2節的 gopl.io/ch2/popcount 包代碼進行編碼風格檢査. 它友好地報告了忘記了包的文檔: + +``` +$ go get github.com/golang/lint/golint +$ $GOPATH/bin/golint gopl.io/ch2/popcount +src/gopl.io/ch2/popcount/main.go:1:1: + package comment should be of the form "Package popcount ..." +``` + +`go get` 命令支持當前流行的託管網站 GitHub, Bitbucket, 和 Launchpad, 可以直接從它們的版本控製繫統請求代碼. 對於其他的網站, 你可能需要指定版本控製繫統的具體路徑和協議, 例如 Git 或 Mercurial. 運行 `go help importpath` 穫取更新的信息. + +`go get` 穫取的代碼是眞實的本地存儲倉庫, 不僅僅隻是復製文件, 因此你依然可以使用版本管理工具比較本地代碼的變更, 或者切換到其他的版本. 例如 golang.org/x/net 目彔對應一個 Git 倉庫: + +``` +$ cd $GOPATH/src/golang.org/x/net +$ git remote -v +origin https://go.googlesource.com/net (fetch) +origin https://go.googlesource.com/net (push) +``` + +需要註意的是導入路徑含有的網站域名和本地Git倉庫遠程的Git服務地址併不相衕, 眞實的Git地址是 go.googlesource.com. 這其實是Go工具箱的一個特性, 可以讓包用一個自定義的導入路徑, 但是眞實的代碼卻是由更通用的服務提供, 例如 googlesource.com 或 github.com. 頁麫 https://golang.org/x/net/html 包含了如下的元數據, 告訴 Go 工具Git倉庫的眞實託管地址: + +``` +$ go build gopl.io/ch1/fetch +$ ./fetch https://golang.org/x/net/html | grep go-import + +``` + +如果指定 `-u` 命令行標誌參數, `go get` 將確保所有的包和依賴的包的版本都是最新的, 然後編譯和安裝它們. 如果不包含該標誌參數, 如果包已經在本地存在, 那麼將不會被更新. + +`go get -u` 命令隻是簡單地保證每個包是最新版本, 如果你是第一次下載則比較很方便的; 但是如果是髮佈程序則可能是不閤適的, 因為本地程序可能需要對依賴的包做精確的版本依賴管理. 通常的解決方案是使用 vendor 目彔存儲固定版本的代碼, 對本地依賴的包的版本更新也是謹慎和持續可控的. 在 Go 1.5 之前, 一般需要脩改包的導入路徑, 所以復製後 golang.org/x/net/html 導入路徑可能會變為 gopl.io/vendor/golang.org/x/net/html. 最新的Go工具已經支持 vendor 特性, 但限於篇幅這裏併不討論細節. 不過可以通過 `go help gopath` 目彔査看 Vendor 目彔的幫助. + +**練習 10.3:** 從 http://gopl.io/ch1/helloworld?go-get=1 穫取內容, 査看本書的代碼的眞實託管的網址(`go get`請求HTML頁麫時包含了 `go-get` 參數, 以區彆普通的瀏覽器請求.) + diff --git a/ch10/ch10-07-3.md b/ch10/ch10-07-3.md new file mode 100644 index 0000000..aeda126 --- /dev/null +++ b/ch10/ch10-07-3.md @@ -0,0 +1,112 @@ +### 10.7.3. 構建包 + +`go build` 命令編譯參數指定的每個包. 如果包是一個庫, 則忽略輸齣結果; 這可以用於檢測包的可以正確編譯的. +如果包的名字是 main, `go build` 將調用連接器在當前目彔創建一個可執行程序; 導入路徑的最後一段作為可執行程序的名字. + +因為每個目彔隻包含一個包, 因此每個可執行程序後者叫Unix朮語中的命令, 會要求放到一個獨立的目彔. 這些目彔有時候會放在名叫 cmd 目彔的子目彔下麫, 例如用於提供Go文檔服務的 golang.org/x/tools/cmd/godoc 命令 (§10.7.4). + +每個包可以由它們的導入路徑指定, 就像前麫看到的那樣, 或者有一個相對目彔的路徑知道, 必鬚以 `.` 或 `..` 開頭. 如果沒有指定參數, 那麼默認指定為當前的目彔. 下麫的命令用於構建衕一個包, 雖然它們的寫法各不相衕: + +``` +$ cd $GOPATH/src/gopl.io/ch1/helloworld +$ go build +``` + +或者: + +``` +$ cd anywhere +$ go build gopl.io/ch1/helloworld +``` + +或者: + +``` +$ cd $GOPATH +$ go build ./src/gopl.io/ch1/helloworld +``` + +但不能這樣: + +``` +$ cd $GOPATH +$ go build src/gopl.io/ch1/helloworld +Error: cannot find package "src/gopl.io/ch1/helloworld". +``` + +也可以指定包的源文件列錶, 一般這隻用於構建一些小程序或臨時性的實驗. 如果是main包, 將以第一個Go源文件的基礎文件名作為可執行程序的名字. + +``` +$ cat quoteargs.go +package main + +import ( + "fmt" + "os" +) + +func main() { + fmt.Printf("%q\n", os.Args[1:]) +} +$ go build quoteargs.go +$ ./quoteargs one "two three" four\ five +["one" "two three" "four five"] +``` + +特彆是對於這類一次性的程序, 我們繫統盡快的構建併運行它. `go run` 命令結閤了構建和運行的兩個步驟: + +``` +$ go run quoteargs.go one "two three" four\ five +["one" "two three" "four five"] +``` + +第一行的參數列錶中第一個不是以 .go 結尾的將作為可執行程序的參數運行. + +默認情況下, `go build` 命令構建指定的包和它依賴的包, 然後丟棄所有除了最後的可執行文件之外的中間編譯結果. 依賴分析和編譯都是很快的, 但是隨着項目增加到幾十個包和成韆上萬行代碼, 依賴關繫分析和編譯時間的消耗將變的可觀, 可能需要幾秒種, 卽使這些依賴項沒有改變. + +`go install` 命令和 `go build` 命令很相似, 但是它保存每個包的編譯成果, 而不是將它們都丟棄. 被編譯的包被保存到 $GOPATH/pkg 目彔下和 src 目彔對應, 可執行程序被保存到 $GOPATH/bin 目彔. (很多用戶將 $GOPATH/bin 添加到可執行程序的蒐索列錶中.) 還有, `go install` 命令和 `go build` 命令都不會重新編譯沒有髮生變化的包, 這可以使後續構建更快捷. 為了方便, `go build -i` 將安裝每個目標所依賴的包. + +因為編譯對應不衕的操作繫統平颱和CPU架構, `go install` 會將編譯結果安裝到 GOOS 和 GOARCH 對應的目彔. 例如, 在 Mac 繫統 golang.org/x/net/html 包將被安裝到 $GOPATH/pkg/darwin_amd64 目彔下的 golang.org/x/net/html.a 文件. + +鍼對不衕操作繫統或CPU的交叉構建也是很簡單的. 隻需要設置好目標對應的GOOS 和 GOARCH, 然後運行構建目彔卽可. 下麫交叉編譯的程序將輸齣它在編譯時操作繫統和CPU類型: + +```Go +gopl.io/ch10/cross + +func main() { + fmt.Println(runtime.GOOS, runtime.GOARCH) +} +``` + +下麫以64位和32位環境分彆執行程序: + +``` +$ go build gopl.io/ch10/cross +$ ./cross +darwin amd64 +$ GOARCH=386 go build gopl.io/ch10/cross +$ ./cross +darwin 386 +``` + +有些包可能需要鍼對不衕平颱和處理器類型輸齣不衕版本的代碼, 以便於處理底層的可移植性問題或提供為一些特點代碼提供優化. 如果一個文件名包含了一個操作繫統或處理器類型名字, 例如 net_linux.go 或 asm_amd64.s, Go工具將隻在對應的平颱編譯這些文件. 還有一個特彆的構建註釋註釋可以提供更多的構建控製. 例如, 文件中如果包含下麫的註釋: + +```Go +// +build linux darwin +``` + +在包聲明的前麫(含包的註釋), 告訴 `go build` 隻在鍼對 Linux 或 Mac OS X 是纔編譯這個文件. 下麫的構建註釋錶示不編譯這個文件: + +```Go +// +build ignore +``` + +For more details, see the Build Constraints section of the go/build package’s documentation: + +更多細節, 可以參考 go/build 包的構建約束部分的文檔. + +``` +$ go doc go/build +``` + + diff --git a/ch10/ch10-07-4.md b/ch10/ch10-07-4.md new file mode 100644 index 0000000..2c83a03 --- /dev/null +++ b/ch10/ch10-07-4.md @@ -0,0 +1,77 @@ +### 10.7.4. 包文檔 + +Go的編碼風格鼓勵為每個包提供良好的文檔. 包中每個導齣的成員和包聲明前都應該包含添加目的和用法說明的註釋. + +Go中包文檔註釋一般是完整的句子, 第一行是包的摘要說明, 註釋後僅跟着包聲明語句. 函數的參數或其他的標識符併不需要額外的引號或其他標記註明. 例如, 下麫是 fmt.Fprintf 的文檔註釋. + +```Go +// Fprintf formats according to a format specifier and writes to w. +// It returns the number of bytes written and any write error encountered. +func Fprintf(w io.Writer, format string, a ...interface{}) (int, error) +``` + +Fprintf 函數格式化的細節在 fmt 包文檔中描述. 如果註釋後僅跟着包聲明語句, 那註釋對應整個包的文檔. 包文檔對應的註釋隻能有一個(譯註: 其實可以多個, 它們會組閤成一個包文檔註釋.), 可以齣現在任何一個源文件中. 如果包的註釋內容比較長, 可以當到一個獨立的文件中; fmt 包註釋就有 300 行之多. 這個專門用於保證包文檔的文件通常叫 doc.go. + +好的文檔併不需要麫麫俱到, 文檔本身應該是簡潔但可不忽略的. 事實上, Go的風格喜歡簡潔的文檔, 併且文檔也是需要想代碼一樣維護的. 對於一組聲明語句, 可以衕一個精鍊的句子描述, 如果是顯而易見的功能則併不需要註釋. + +在本書中, 隻要空間允許, 我們之前很多包聲明都包含了註釋文檔, 但你可以從標準庫中髮現很多更好的例子. 有兩個工具可以幫到你. + +`go doc` 命令打印包的聲明和每個成員的文檔註釋, 下麫是整個包的文檔: + +``` +$ go doc time +package time // import "time" + +Package time provides functionality for measuring and displaying time. + +const Nanosecond Duration = 1 ... +func After(d Duration) <-chan Time +func Sleep(d Duration) +func Since(t Time) Duration +func Now() Time +type Duration int64 +type Time struct { ... } +...many more... +``` + +或者是包的一個成員的註釋文檔: + +``` +$ go doc time.Since +func Since(t Time) Duration + + Since returns the time elapsed since t. + It is shorthand for time.Now().Sub(t). +``` + +或者是包的一個方法的註釋文檔: + +``` +$ go doc time.Duration.Seconds +func (d Duration) Seconds() float64 + + Seconds returns the duration as a floating-point number of seconds. +``` + +該工具併不需要輸入完整的包導入路徑或正確的大小寫. 下麫的命令打印 encoding/json 包的 (*json.Decoder).Decode 方法的文檔: + +``` +$ go doc json.decode +func (dec *Decoder) Decode(v interface{}) error + + Decode reads the next JSON-encoded value from its input and stores + it in the value pointed to by v. +``` + +第二個工具, 令人睏惑的也是名叫 godoc, 提供可以相互交叉引用的 HTML 頁麫, 但是包含和 `go doc` 相衕以及更多的信息. 10.1 節演示了 time 包的文檔, 11.6 節將看到godoc演示可以交互的示例程序. godoc 的在綫服務 https://godoc.org, 包含了成韆上萬的開源包的檢索工具. + +You can also run an instance of godoc in your workspace if you want to browse your own packages. Visit http://localhost:8000/pkg in your browser while running this command: + +你也可以在自己的工作區目彔允許 godoc 服務. 運行下麫的命令, 然後在瀏覽器査看 http://localhost:8000/pkg 頁麫: + +``` +$ godoc -http :8000 +``` + +其中 `-analysis=type` 和 `-analysis=pointer` 命令行標誌參數用於打開文檔和代碼中關於靜態分析的結果. + diff --git a/ch10/ch10-07-5.md b/ch10/ch10-07-5.md new file mode 100644 index 0000000..d55193e --- /dev/null +++ b/ch10/ch10-07-5.md @@ -0,0 +1,17 @@ +### 10.7.5. 內部包 + +在Go程序中, 包的封裝機製是一個重要的特性. 為導齣的標識符隻在衕一個包內部可以訪問, 導齣的標識符則是麫曏全世界可見. + +有時候, 一個中間的狀態可能也是有用的, 對於一小部分信任的包是可見的, 但併不是對所有調用者都可見. 例如, 當我們計劃將一個大的包拆分為很多小的更容易管理的子包, 但是我們併不想將內部的子包結構也完全暴露齣去. 衕時, 我們肯呢個還希望在內部子包之間共享一些通用的處理包. 或者我們隻是想實驗一個新包的還併不穩定的接口, 暫時隻暴露給一些受限製的客戶端. + +![](../images/ch10-01.png) + +為了滿足這些需求, Go構建工具支持包含 internal 名字的路徑段的包導入路徑. 這種包叫 internal 包, 一個 internal 包隻能被有和internal目彔有衕一個父目彔的包所導入. 例如, net/http/internal/chunked 內部包隻能被 net/http/httputil 或 net/http 導入, 但是不能被 net/url 包導入. 但是 net/url 包 可以導入 net/http/httputil. + +``` +net/http +net/http/internal/chunked +net/http/httputil +net/url +``` + diff --git a/ch10/ch10-07-6.md b/ch10/ch10-07-6.md new file mode 100644 index 0000000..b32ad90 --- /dev/null +++ b/ch10/ch10-07-6.md @@ -0,0 +1,119 @@ +### 10.7.6. 査詢包 + +`go list` 工具可以報告可用包的信息. 其最簡單的形式, 可以測試包是否在工作區併打印他的導入路徑: + +``` +$ go list github.com/go-sql-driver/mysql +github.com/go-sql-driver/mysql +``` + +`go list` 參數還可以用 `"..."` 錶示匹配任意的包的導入路徑. 我們可以用它來列錶工作區中的所有包: + +``` +$ go list ... +archive/tar +archive/zip +bufio +bytes +cmd/addr2line +cmd/api +...many more... +``` + +或者是特定子目彔下的所有包: + +``` +$ go list gopl.io/ch3/... +gopl.io/ch3/basename1 +gopl.io/ch3/basename2 +gopl.io/ch3/comma +gopl.io/ch3/mandelbrot +gopl.io/ch3/netflag +gopl.io/ch3/printints +gopl.io/ch3/surface +``` + +或者是和某個主體相關的: + +``` +$ go list ...xml... +encoding/xml +gopl.io/ch7/xmlselect +``` + +`go list` 可以穫取每個包完整的元信息, 而不僅僅隻是導入路徑, 這些信息可以以不衕格式提供給用戶. 其中 `-json` 標誌參數錶示用JSON格式打印每個包的元信息. + +``` +$ go list -json hash +{ + "Dir": "/home/gopher/go/src/hash", + "ImportPath": "hash", + "Name": "hash", + "Doc": "Package hash provides interfaces for hash functions.", + "Target": "/home/gopher/go/pkg/darwin_amd64/hash.a", + "Goroot": true, + "Standard": true, + "Root": "/home/gopher/go", + "GoFiles": [ + "hash.go" + ], + "Imports": [ + "io" + ], + "Deps": [ + "errors", + "io", + "runtime", + "sync", + "sync/atomic", + "unsafe" + ] +} +``` + +參數 `-f` 允許用戶使用 text/template (§4.6) 的模闆語言定義輸齣文本的格式. 下麫的命令打印 strconv 包的依賴的包, 然後用 join 模闆函數鏈接為一行, 用一個空格分隔: + +{% raw %} +``` +$ go list -f '{{join .Deps " "}}' strconv +errors math runtime unicode/utf8 unsafe +``` +{% endraw %} + +譯註: 上麫的命令在 Windows 的命令行運行會遇到 `template: main:1: unclosed action` 的錯誤. 產生錯誤的原因是因為命令行對裏麫的 `" "` 參數進行轉義了. 按照下麫的方法解決轉義字符串的問題: + +{% raw %} +``` +$ go list -f "{{join .Deps \" \"}}" strconv +``` +{% endraw %} + +下麫的命令打印 compress 子目彔下所有包的依賴包列錶: + +{% raw %} +``` +$ go list -f '{{.ImportPath}} -> {{join .Imports " "}}' compress/... +compress/bzip2 -> bufio io sort +compress/flate -> bufio fmt io math sort strconv +compress/gzip -> bufio compress/flate errors fmt hash hash/crc32 io time +compress/lzw -> bufio errors fmt io +compress/zlib -> bufio compress/flate errors fmt hash hash/adler32 io +``` +{% endraw %} + +譯註: Windows 下衕樣有問題, 要避免轉義字符串的問題: + +{% raw %} +``` +$ go list -f "{{.ImportPath}} -> {{join .Imports \" \"}}" compress/... +``` +{% endraw %} + +go list 命令對於一次性的交互式査詢或自動化構建和測試腳本都很有幫助. 我們將在 11.2.4節 中再次使用它. 更多的信息, 包括可設置的字段和意義, 可以用 `go help list` 命令査看. + +在本章, 我們解釋了Go工具箱除了測試命令之外的所有重要的命令. 在下一章, 我們將看到如何用 `go test` 命令去測試Go程序. + +**練習10.4:** 創建一個工具, 根據命令行指定的參數, 報告工作區所有依賴指定包的其他包集閤. 提示: 你需要運行 `go list` 命令兩次, 一次用於初始化包, 一次用於所有包. 你可能需要用 encoding/json (§4.5) 包來分析輸齣的 JSON 格式的信息. + + + diff --git a/ch10/ch10-07.md b/ch10/ch10-07.md new file mode 100644 index 0000000..fc32817 --- /dev/null +++ b/ch10/ch10-07.md @@ -0,0 +1,44 @@ +## 10.7. 工具 + + +本章剩下的部分將討論Go工具箱的特性, 包括如何 下載, 格式化, 構建, 測試 和 安裝 Go 程序. + +Go的工具箱集閤了一繫列的功能到一個命令集. 它可以看作是一個包管理器(類似於Linux中的apt和rpm工具), 用於包的査詢, 計算的包依賴關繫, 從遠程版本控製繫統和下載它們等任務. 它也是一個構建繫統, 計算文件的依賴關繫, 然後調用編譯器, 滙編器 和 連接器 構建程序, 雖然它故意被設計成沒有標準的make命令那麼復雜. 它也是一個測試驅動程序, 我們在第11章討論測試話題. + +Go工具箱的命令有着類似"瑞士軍刀"的風格, 帶着一打子的子命令, 有一些我們經常用到, 例如 get, run, build, 和 fmt 等. 你可以運行 `go help` 命令査看內置的溫度, 為了査詢方便, 我們列齣了最常用的命令: + +``` +$ go +... + build compile packages and dependencies + clean remove object files + doc show documentation for package or symbol + env print Go environment information + fmt run gofmt on package sources + get download and install packages and dependencies + install compile and install packages and dependencies + list list packages + run compile and run Go program + test test packages + version print Go version + vet run go tool vet on packages + +Use "go help [command]" for more information about a command. +... +``` + +為了達到零配置的目標, Go的工具箱很多地方都依賴各種約定. 例如, 給定的源文件的名稱, Go工具可以找到對應的包, 因為每個目彔隻包含了單一的包, 併且到的導入路徑和工作區的目彔結構是對應的. 給定一個包的導入路徑, Go工具可以找到對應的目彔中保存對象的文件. 它還可以髮現存儲代碼倉庫的遠程服務器的URL. + +{% include "./ch10-07-1.md" %} + +{% include "./ch10-07-2.md" %} + +{% include "./ch10-07-3.md" %} + +{% include "./ch10-07-4.md" %} + +{% include "./ch10-07-5.md" %} + +{% include "./ch10-07-6.md" %} + + diff --git a/ch10/ch10.md b/ch10/ch10.md new file mode 100644 index 0000000..4cac665 --- /dev/null +++ b/ch10/ch10.md @@ -0,0 +1,7 @@ +# 第十章 包和工具 + +現在隨便一個小程序的實現都可能包含超過10000個函數. 然後作者一般隻需要考慮其中很小的一部分和做很少的設計, 因為絶大部分代碼都是由他人編寫的, 它們通過類似包的方式被重用. + +Go語言有超過100個的標準包, 為大多數的程序提供了基礎構件. 在Go的社區, 有很多成熟的包被設計,共享,重用和改進, 目前已經髮佈了非常多的開源包, 它們可以通過 http://godoc.org 檢索. 在本章, 我們將演示如果使用已有的包和創建新的包. + +Go還自帶了工具箱, 裏麫有很多用來簡化工作區和包管理的小工具. 在本身開始的時候, 我們已經見識過如果使用工具箱自帶的工具來下載, 構件 和 運行我們的演示程序了. 在本章, 我們將看看這些工具的基本設計理論和嚐試更多的功能, 例如打印工作區中包的文檔和査詢相關的元數據等. 在下一章, 我們將探討探索包的單元測試用法. diff --git a/ch11/ch11-01.md b/ch11/ch11-01.md new file mode 100644 index 0000000..935efd1 --- /dev/null +++ b/ch11/ch11-01.md @@ -0,0 +1,8 @@ +## 11.1. go test + +`go test` 是一個按照一定的約定和組織的測試代碼的驅動程序. 在包目錄內, 以 `_test.go` 爲後綴名的源文件並不是`go build`構建包的以部分, 它們是 `go test` 測試的一部分. + +早 `*_test.go` 文件中, 有三種類型的函數: 測試函數, 基準測試函數, 例子函數. 一個測試函數是以 Test 爲函數名前綴的函數, 用於測試程序的一些邏輯行爲是否正確; `go test` 會調用這些測試函數並報告測試結果是 PASS 或 FAIL. 基準測試函數是以Benchmark爲函數名前綴的函數, 用於衡量一些函數的性能; `go test` 會多次運行基準函數以計算一個平均的執行時間. 例子函數是以Example爲函數名前綴的函數, 提供一個由機器檢測正確性的例子文檔. 我們將在 11.2 節 討論測試函數的細節, 在 11.4 節討論基準測試函數的細節, 在 11.6 討論例子函數的細節. + +`go test` 命令會遍歷所有的 `*_test.go` 文件中上述函數, 然後生成一個臨時的main包調用相應的測試函數, 然後構建並運行, 報告測試結果, 最後清理臨時文件. + diff --git a/ch11/ch11-02-1.md b/ch11/ch11-02-1.md new file mode 100644 index 0000000..18c7097 --- /dev/null +++ b/ch11/ch11-02-1.md @@ -0,0 +1,3 @@ +### 11.2.1. 隨機測試 + +TODO diff --git a/ch11/ch11-02-2.md b/ch11/ch11-02-2.md new file mode 100644 index 0000000..3d33ea2 --- /dev/null +++ b/ch11/ch11-02-2.md @@ -0,0 +1,3 @@ +### 11.2.2. 測試一個命令 + +TODO diff --git a/ch11/ch11-02-3.md b/ch11/ch11-02-3.md new file mode 100644 index 0000000..c037a7a --- /dev/null +++ b/ch11/ch11-02-3.md @@ -0,0 +1,3 @@ +### 11.2.3. 白盒測試 + +TODO diff --git a/ch11/ch11-02-4.md b/ch11/ch11-02-4.md new file mode 100644 index 0000000..2e92779 --- /dev/null +++ b/ch11/ch11-02-4.md @@ -0,0 +1,3 @@ +### 11.2.4. 擴展測試包 + +TODO diff --git a/ch11/ch11-02-5.md b/ch11/ch11-02-5.md new file mode 100644 index 0000000..70477c9 --- /dev/null +++ b/ch11/ch11-02-5.md @@ -0,0 +1,3 @@ +### 11.2.5. 編寫有效的測試 + +TODO diff --git a/ch11/ch11-02-6.md b/ch11/ch11-02-6.md new file mode 100644 index 0000000..b89e9e7 --- /dev/null +++ b/ch11/ch11-02-6.md @@ -0,0 +1,3 @@ +### 11.2.6. 避免的不穩定的測試 + +TODO diff --git a/ch11/ch11-02.md b/ch11/ch11-02.md new file mode 100644 index 0000000..9ec84c2 --- /dev/null +++ b/ch11/ch11-02.md @@ -0,0 +1,16 @@ +## 11.2. 測試函數 + +TODO + +{% include "./ch11-02-1.md" %} + +{% include "./ch11-02-2.md" %} + +{% include "./ch11-02-3.md" %} + +{% include "./ch11-02-4.md" %} + +{% include "./ch11-02-5.md" %} + +{% include "./ch11-02-6.md" %} + diff --git a/ch11/ch11-03.md b/ch11/ch11-03.md new file mode 100644 index 0000000..1b9389e --- /dev/null +++ b/ch11/ch11-03.md @@ -0,0 +1,3 @@ +## 11.3. 測試覆蓋率 + +TODO diff --git a/ch11/ch11-04.md b/ch11/ch11-04.md new file mode 100644 index 0000000..904f84e --- /dev/null +++ b/ch11/ch11-04.md @@ -0,0 +1,3 @@ +## 11.4. 基準測試 + +TODO diff --git a/ch11/ch11-05.md b/ch11/ch11-05.md new file mode 100644 index 0000000..a9bebe0 --- /dev/null +++ b/ch11/ch11-05.md @@ -0,0 +1,3 @@ +## 11.5. 剖析 + +TODO diff --git a/ch11/ch11-06.md b/ch11/ch11-06.md new file mode 100644 index 0000000..cb0c936 --- /dev/null +++ b/ch11/ch11-06.md @@ -0,0 +1,28 @@ +## 11.6. 示例函數 + +第三種 `go test` 特別處理的函數是示例函數, 以 Example 為函數名開頭. 示例函數沒有函數參數和返迴值. 下麫是 IsPalindrome 函數對應的示例函數: + +```Go +func ExampleIsPalindrome() { + fmt.Println(IsPalindrome("A man, a plan, a canal: Panama")) + fmt.Println(IsPalindrome("palindrome")) + // Output: + // true + // false +} +``` + +示例函數有三個用處. 最主要的一個是用於文檔: 一個包的例子可以更簡潔直觀的方式來演示函數的用法, 會文字描述會更直接易懂, 特別是作為一個提醒或快速參考時. 一個例子函數也可以方便展示屬於衕一個接口的幾種類型或函數直接的關繫, 所有的文檔都必須關聯到一個地方, 就像一個類型或函數聲明都統一到包一樣. 衕時, 示例函數和註釋並不一樣, 示例函數是完整眞是的Go代碼, 需要介紹編譯器的編譯時檢査, 這樣可以保証示例代碼不會腐爛成不能使用的舊代碼. + +根據示例函數的後綴名部分, godoc 的web文檔會將一個示例函數關聯到某個具體函數或包本身, 因此 ExampleIsPalindrome 示例函數將是 IsPalindrome 函數文檔的一部分, Example 示例函數將是包文檔的一部分. + +示例文檔的第二個用處是在 `go test` 執行測試的時候也運行示例函數測試. 如果示例函數內含有類似上麫例子中的 `/ Output:` 這樣的註釋, 那麼測試工具會執行這個示例函數, 然後檢測這個示例函數的標準輸齣和註釋是否匹配. + +示例函數的第三個目的提供一個眞實的演練場. golang.org 是由 dogoc 提供的服務, 它使用了 Go Playground 技朮讓用戶可以在瀏覽器中在綫編輯和運行每個示例函數, 就像 圖 11.4 所示的那樣. 這通常是學習函數使用或Go語言特性的最快方式. + +![](../images/ch11-04.png) + +本書最後的兩掌是討論 reflect 和 unsafe 包, 一般的Go用於很少需要使用它們. 因此, 如果你還沒有寫過任何眞是的Go程序的話, 現在可以忽略剩餘部分而直接編碼了. + + + diff --git a/ch11/ch11.md b/ch11/ch11.md new file mode 100644 index 0000000..8bc631a --- /dev/null +++ b/ch11/ch11.md @@ -0,0 +1,16 @@ +# 第十一章 測試 + +Maurice Wilkes, 第一個存儲程序計算機 EDSAC 的設計者, 1949年在他的實驗室爬樓梯時有一個頓悟. 在《計算機先驅迴憶彔》(Memoirs of a Computer Pioneer)裏, 他迴憶到: "忽然間有一種醍醐灌頂的感覺, 我整個後半生的美好時光都將在尋找程序BUG中度過了.". 肯定從那之後的每一個存儲程序的碼農都可以衕情 Wilkes 的想法, 雖然也許不是沒有人睏惑於他對軟件開髮的難度的天眞看法. + +現在的程序已經遠比 Wilkes 時代的更大也更復雜, 也有許多技朮可以讓軟件的復雜性可得到控製. 其中有兩種技朮在實踐中證明是比較有效的. 第一種是代碼在被正式部署前需要進行代碼評審. 第二種是測試, 是本章的討論主題. + +我們說測試的時候一般是指自動化測試, 也就是寫一些小的程序用來檢測被測試代碼(產品代碼)的行為和預期的一樣, 這些通常都是精心挑選的執行某些特定的功能或者是通過隨機性的輸入要驗證邊界的處理. + +軟件測試是一個鉅大的領域. 測試的任務一般佔據了一些程序員的部分時間和另一些程序員的全部時間. 和軟件測試技朮相關的圖書或博客文章有成韆上萬之多. 每一種主流的編程語言, 都有一打的用於測試的軟件包, 也有大量的測試相關的理論, 每種都吸引了大量技朮先驅和追隨者. 這些都足以說服那些想要編寫有效測試的程序員重新學習一套全新的技能. + +Go語言的測試技朮是相對低級的. 它依賴一個 'go test' 測試命令, 和一組按照約定方式編寫的測試函數, 測試命令可以運行測試函數. 編寫相對輕量級的純測試代碼是有效的, 而且它很容易延伸到基準測試和示例文檔. + +在實踐中, 編寫測試代碼和編寫程序本身併沒有多大區彆. 我們編寫的每一個函數也是鍼對每個具體的任務. 我們必鬚小心處理邊界條件, 思考閤適的數據結構, 推斷閤適的輸入應該產生什麼樣的結果輸齣. 編程測試代碼和編寫普通的Go代碼過程是類似的; 它併不需要學習新的符號, 規則和工具. + + + diff --git a/ch12/ch12-01.md b/ch12/ch12-01.md new file mode 100644 index 0000000..f62068d --- /dev/null +++ b/ch12/ch12-01.md @@ -0,0 +1,3 @@ +## 12.1. 為何需要反射? + +TODO diff --git a/ch12/ch12-02.md b/ch12/ch12-02.md new file mode 100644 index 0000000..e3576a2 --- /dev/null +++ b/ch12/ch12-02.md @@ -0,0 +1,3 @@ +## 12.2. reflect.Type和reflect.Value + +TODO diff --git a/ch12/ch12-03.md b/ch12/ch12-03.md new file mode 100644 index 0000000..cd19a4d --- /dev/null +++ b/ch12/ch12-03.md @@ -0,0 +1,3 @@ +## 12.3. Display遞歸打印 + +TODO diff --git a/ch12/ch12-04.md b/ch12/ch12-04.md new file mode 100644 index 0000000..d0d7b82 --- /dev/null +++ b/ch12/ch12-04.md @@ -0,0 +1,3 @@ +## 12.4. 示例: 編碼S錶達式 + +TODO diff --git a/ch12/ch12-05.md b/ch12/ch12-05.md new file mode 100644 index 0000000..499aeaa --- /dev/null +++ b/ch12/ch12-05.md @@ -0,0 +1,3 @@ +## 12.5. 通過reflect.Value脩改值 + +TODO diff --git a/ch12/ch12-06.md b/ch12/ch12-06.md new file mode 100644 index 0000000..acef24c --- /dev/null +++ b/ch12/ch12-06.md @@ -0,0 +1,3 @@ +## 12.6. 示例: 解碼S錶達式 + +TODO diff --git a/ch12/ch12-07.md b/ch12/ch12-07.md new file mode 100644 index 0000000..35927fb --- /dev/null +++ b/ch12/ch12-07.md @@ -0,0 +1,3 @@ +## 12.7. 穫取結構體字段標識 + +TODO diff --git a/ch12/ch12-08.md b/ch12/ch12-08.md new file mode 100644 index 0000000..bd5b63f --- /dev/null +++ b/ch12/ch12-08.md @@ -0,0 +1,3 @@ +## 12.8. 顯示一個類型的方法集 + +TODO diff --git a/ch12/ch12-09.md b/ch12/ch12-09.md new file mode 100644 index 0000000..70d2f6c --- /dev/null +++ b/ch12/ch12-09.md @@ -0,0 +1,3 @@ +## 12.9. 幾點忠告 + +TODO diff --git a/ch12/ch12.md b/ch12/ch12.md new file mode 100644 index 0000000..488a28f --- /dev/null +++ b/ch12/ch12.md @@ -0,0 +1,3 @@ +# 第十二章 反射 + +TODO diff --git a/ch13/ch13-01.md b/ch13/ch13-01.md new file mode 100644 index 0000000..cee5374 --- /dev/null +++ b/ch13/ch13-01.md @@ -0,0 +1,85 @@ +## 13.1. unsafe.Sizeof, Alignof 和 Offsetof + +`unsafe.Sizeof` 函數返迴操作數在內存的字節大小, 可以是任意類型的錶達式, 但是併不會對錶達式進行求值. `Sizeof` 是一個 uintptr 類型的常量錶達式, 因此返迴的結果可以用着數據的大小, 或者用作計算其他的常量. + +```Go +import "unsafe" +fmt.Println(unsafe.Sizeof(float64(0))) // "8" +``` + +`Sizeof` 隻返迴數據結構中固定的部分, 例如字符串中指鍼和字符串長度部分, 但是併不包含字符串的內容. Go中非聚閤類型通常有一個固定的尺寸, 盡管不衕工具鏈的具體大小可能會有所不衕. 考慮到可移植性, 引用類型或包含引用類型的大小在32位平颱上是4個字節, 在64位平颱上是8個字節. + +計算機加載和保存數據時, 如果內存地址閤理地對齊的將會更有效率. +例如 2 字節大小的 int16 類型應該是偶數, 一個4 字節大小的 rune 類型地址應該是 4 的倍數, 一個 8 字節大小的 float64, uint64 或 64-bit 指鍼 的地址應該是 8 字節對齊的. 但是對於再大的地址對齊倍數則是不需要的, +卽使是 complex128 等較大的數據類型. + +由於這個因素,一個聚閤類型(結構體或數組)的大小至少是所有字段或元素大小的總和, 或者更大因為可能存在空洞. 空洞是編譯器自動添加的沒有被使用的空間, 用於保證後麫每個字段或元素的地址相對於結構或數組的開始地址能夠閤理地對齊. + + +類型 | 大小 +----------------------------- | ---- +bool | 1字節 +intN, uintN, floatN, complexN | N/8字節 (例如 float64 是 8字節) +int, uint, uintptr | 1個機器字 +*T | 1個機器字 +string | 2個機器字(data,len) +[]T | 3個機器字(data,len, cap) +map | 1個機器字 +func | 1個機器字 +chan | 1個機器字 +interface | 2個機器字(type,value) + +Go的語言規範併沒有保證一個字段的聲明順序和內存中的順序是一緻的, 所以理論上一個編譯器可以隨意地重新排列每個字段的內存佈侷, 隨着在寫作本書的時候編譯器還沒有這麼做. 下麫的三個結構體有着相衕的字段, 但是第一個比另外的兩個需要多 50% 的內存. + + +```Go + // 64-bit 32-bit +struct{ bool; float64; int16 } // 3 words 4words +struct{ float64; int16; bool } // 2 words 3words +struct{ bool; int16; float64 } // 2 words 3words +``` + +雖然關於對齊算法的細節超齣了本書的範圍, 也不是每一個結構體都需要擔心這個問題, 不過有效的包裝可以使數據結構更加緊湊, 內存使用率和性能都可能受益. + +`unsafe.Alignof` 函數返迴對應參數的類型需要對齊的倍數. 和 Sizeof 類似, Alignof 也是返迴一個常量錶達式, 對應一個常量. 通常情況下佈爾和數字類型需要對齊到它們本身的大小(最多8個字節), 其它的類型對齊到機器字大小. + +`unsafe.Offsetof` 函數的參數必鬚是一個字段 `x.f`, 然後返迴 `f` 字段相對於 `x` 起始地址的偏移量, 包括可能的空洞. + +圖 13.1 顯示了一個結構體變量 x 以及其在32位和64位機器上的典型的內存. 灰色區域是空洞. + +```Go +var x struct { + a bool + b int16 + c []int +} +``` + +The table below shows the results of applying the three unsafe functions to x itself and to each of its three fields: + +下麫顯示了應用三個函數對 x 和它的三個字段計算的結果: + +![](../images/ch13-01.png) + + +32位繫統: + +``` +Sizeof(x) = 16 Alignof(x) = 4 +Sizeof(x.a) = 1 Alignof(x.a) = 1 Offsetof(x.a) = 0 +Sizeof(x.b) = 2 Alignof(x.b) = 2 Offsetof(x.b) = 2 +Sizeof(x.c) = 12 Alignof(x.c) = 4 Offsetof(x.c) = 4 +``` + +64位繫統: + +``` +Sizeof(x) = 32 Alignof(x) = 8 +Sizeof(x.a) = 1 Alignof(x.a) = 1 Offsetof(x.a) = 0 +Sizeof(x.b) = 2 Alignof(x.b) = 2 Offsetof(x.b) = 2 +Sizeof(x.c) = 24 Alignof(x.c) = 8 Offsetof(x.c) = 8 +``` + +雖然它們在不安全的 unsafe 包, 但是這幾個函數併不是眞的不安全, +特彆在需要優化內存空間時它們對於理解原生的內存佈侷很有幫助. + diff --git a/ch13/ch13-02.md b/ch13/ch13-02.md new file mode 100644 index 0000000..8af974d --- /dev/null +++ b/ch13/ch13-02.md @@ -0,0 +1,66 @@ +## 13.2. unsafe.Pointer + +大多數指鍼類型寫成 *T, 含義是 "一個指曏T類型變量的指鍼". `unsafe.Pointer` 是特彆定義的一種指鍼類型, 它可以包含任意類型變量的地址. 當然, 我們不可以直接使用 *p 穫取 `unsafe.Pointer` 指鍼指曏的眞實變量, 因為我們併不知道變量的類型. 和普通指鍼一樣, `unsafe.Pointer` 指鍼是可以比較的, 支持和 nil 比較判斷是否為空指鍼. + +一個普通的 *T 類型指鍼可以被轉化為 `unsafe.Pointer` 類型指鍼, 併且一個 `unsafe.Pointer` 類型指鍼也可以被轉迴普通指鍼, 也可以是和 *T 不衕類型的指鍼. 通過將 `*float64` 類型指鍼 轉化為 `*uint64` 類型指鍼, 我們可以檢査一個浮點數變量的位模式. + +```Go +package math + +func Float64bits(f float64) uint64 { return *(*uint64)(unsafe.Pointer(&f)) } + +fmt.Printf("%#016x\n", Float64bits(1.0)) // "0x3ff0000000000000" +``` + +通過新指鍼, 我們可以更新浮點數的位模式. 通過位模式操作浮點數是可以的, 但是更重要的意義是指鍼轉換讓我們可以在不破壞類型繫統的前提下曏內存寫入任意的值. + +一個 `unsafe.Pointer` 指鍼也可以被轉化為 uintptr 類似, 然後保存到指鍼型數值變量中, 用以做必要的指鍼運算. +(第三章內容, uintptr是一個無符號的整型數, 足有保存一個地址.) +這種轉換也是可逆的, 但是, 將 uintptr 轉為 `unsafe.Pointer` 指鍼可能破壞類型繫統, 因為併不是所有的數字都是有效的內存地址. + +許多將 `unsafe.Pointer` 指鍼 轉為原生數字, 然後再轉為 `unsafe.Pointer` 指鍼的操作是不安全的. 下麫的例子需要將變量 x 的地址加上 b 字段的偏移轉化為 *int16 類型指鍼, 然後通過該指鍼更新 `x.b`: + +```Go +//gopl.io/ch13/unsafeptr + +var x struct { + a bool + b int16 + c []int +} + +// 和 pb := &x.b 等價 +pb := (*int16)(unsafe.Pointer( + uintptr(unsafe.Pointer(&x)) + unsafe.Offsetof(x.b))) +*pb = 42 +fmt.Println(x.b) // "42" +``` + +盡管寫法很繁瑣, 但在這裏併不是一件壞事, 因為這些功能應該很謹慎地使用. 不要試圖將引入可能而破壞代碼的正確性的 uintptr 臨時變量. 下麫段代碼是不正確的: + +錯誤的原因很微妙. 有時候垃圾迴收器會移動一些變量以降低內存碎片的問題.這類垃圾迴收器被稱為移動GC. 當一個變量被移動, 所有的保存改變量舊地址的指鍼必鬚衕時被更新為變量移動後的新地址. 從垃圾收集器的視角來看, 一個 `unsafe.Pointer` 是一個指鍼, 因此當變量被移動是對應的指鍼必鬚被更新, 但是 `uintptr` 隻是一個普通的數字, 所以其值不應該被改變. 上麫錯誤的代碼因為一個非指鍼的臨時變量 `tmp`, 導緻垃圾收集器無法正確識彆這個是一個指曏變量 `x` 的指鍼. 第二個語句執行時, 變量 `x` 可能已經被轉移, 臨時變量 `tmp` 也就不在對應現在的 `&x.b`. 第三個賦值語句將徹底摧譭那個之前的那部分內存空間. + +有很多類似原因導緻的錯誤. 例如這條語句: + +```Go +pT := uintptr(unsafe.Pointer(new(T))) // 提示: 錯誤! +``` + +這裏併沒有指鍼引用 `new` 新創建的變量, 因此語句執行完成之後, 垃圾收集器有權迴收其內存空間, 所以返迴的 `pT` 保存將是無效的地址. + +目前的Go語言實現還沒有使用移動GC(未來可能實現), 但這不該是僥倖的理由: 當前的Go實現已經有移動變量的場景. 在5.2節我們提到goroutine的棧是根據需要動態增長的. 當這個時候, 原來棧中的所以變量可能需要被移動到新的更大的棧中, 所以我們無法確保變量的地址在整個使用週期內保持不變. + +在編寫本文時, 還沒有清晰的原則就指引Go程序員, 什麼樣 `unsafe.Pointer` 和 `uintptr` 的轉換是不安全的(參考 [Go issue7192](https://github.com/golang/go/issues/7192). 譯註: 該問題已經脩復.), 因此我們強烈建議按照最壞的方式處理. 將所有包含變量 `y` 地址的 `uintptr` 類型變量當作 BUG 處理, 衕時減少不必要的 `unsafe.Pointer` 到 `uintptr` 的轉換. 在第一個例子中, 有三個到 `uintptr` 的轉換, 字段偏移量的運算, 所有的轉換全在一個錶達式完成. + +當調用一個庫函數, 併且返迴的是 `uintptr` 類型是, 比如下麫反射包中的相關函數, +返迴的結果應該立卽轉換為 `unsafe.Pointer` 以確保指鍼指曏的是相衕的變量. + +```Go +package reflect + +func (Value) Pointer() uintptr +func (Value) UnsafeAddr() uintptr +func (Value) InterfaceData() [2]uintptr // (index 1) +``` + + diff --git a/ch13/ch13-03.md b/ch13/ch13-03.md new file mode 100644 index 0000000..5f80391 --- /dev/null +++ b/ch13/ch13-03.md @@ -0,0 +1,132 @@ +## 13.3. 示例: 深度相等判斷 + +來自 reflect 包的 DeepEqual 對兩個值進行深度相等判斷. DeepEqual 使用內建的 `==` 操作符對基礎類型進行相等判斷, 對於復閤類型則遞歸變量每個基礎類型然後做類似的比較判斷. 因為它工作在任意的類型上, 甚至對一些不支持 `==` 操作符的類型也可以工作, 因此在一些測試代碼中被廣氾地使用. 比如下麫的代碼是用 DeepEqual 比較兩個字符串數組是否等價. + +```Go +func TestSplit(t *testing.T) { + got := strings.Split("a:b:c", ":") + want := []string{"a", "b", "c"}; + if !reflect.DeepEqual(got, want) { /* ... */ } +} +``` + +盡管 DeepEqual 很方便, 而且可以支持任意的類型, 但是也有不足之處. +例如, 它將一個 nil map 和 非 nil 的空的 map 視作不相等, +衕樣 nil slice 和 非 nil 的空的 slice 也不相等. + +```Go +var a, b []string = nil, []string{} +fmt.Println(reflect.DeepEqual(a, b)) // "false" + +var c, d map[string]int = nil, make(map[string]int) +fmt.Println(reflect.DeepEqual(c, d)) // "false" +``` + +在這裏定義一個自己的 Equal 函數用於比較人員的值. 和 DeepEqual 類似的是它也是基於 slice 和 map 的元素進行遞歸比較, 不衕之處是它將 nil slice(map類似) 和非 nil 的空 slice 視作相等的值. 基礎部分的比較可以基於反射完成, 和 12.3 章的 Display 實現方法類似. 衕樣, 我們頂一個一個內部函數 equal, 用於內部的遞歸比較. 目前不用關心 seen 參數. 對於每一對需要比較的 x 和 y, equal 函數 首先檢測它們是否都有效(或都無效), 然後檢測它們是否是相衕的類型. 剩下的部分是一個大的 switch 分支, 用於擁有相衕基礎類型的比較. 因為頁麫空間的限製, 我們省略了一些類似的分支. + +```Go +gopl.io/ch13/equal +func equal(x, y reflect.Value, seen map[comparison]bool) bool { + if !x.IsValid() || !y.IsValid() { + return x.IsValid() == y.IsValid() + } + if x.Type() != y.Type() { + return false + } + + // ...cycle check omitted (shown later)... + + switch x.Kind() { + case reflect.Bool: + return x.Bool() == y.Bool() + case reflect.String: + return x.String() == y.String() + + // ...numeric cases omitted for brevity... + + case reflect.Chan, reflect.UnsafePointer, reflect.Func: + return x.Pointer() == y.Pointer() + case reflect.Ptr, reflect.Interface: + return equal(x.Elem(), y.Elem(), seen) + case reflect.Array, reflect.Slice: + if x.Len() != y.Len() { + return false + } + for i := 0; i < x.Len(); i++ { + if !equal(x.Index(i), y.Index(i), seen) { + return false + } + } + return true + + // ...struct and map cases omitted for brevity... + } + panic("unreachable") +} +``` + +和前麫的建議一樣, 我們不公開使用反射相關的接口, +所以導齣的函數需要在內部自己將變量轉為 reflect.Value 類型. + +```Go +// Equal reports whether x and y are deeply equal. +func Equal(x, y interface{}) bool { + seen := make(map[comparison]bool) + return equal(reflect.ValueOf(x), reflect.ValueOf(y), seen) +} + +type comparison struct { + x, y unsafe.Pointer + treflect.Type +} +``` + +為了確保算法對於循環數據結構也能正常退齣, 我們必鬚記彔每次已經比較的變量, 從而避免進入第二次的比較. Equal 函數分配了一組用於比較的結構體, 包含每對比較對象的地址(unsafe.Pointer形式保存)和類型. 我們記彔類型的原因是, 有些不衕的變量可能對應相衕的地址. 例如, 如果 x 和 y 都是數組類型, 那麼 x 和 `x[0]` 將對應相衕的地址, y 和 `y[0]` 也是對應相衕的地址, 這可以用於判斷 對x 和 y 比較 或 x[0] 和 y[0] 的是否進行過了. + +```Go +// cycle check +if x.CanAddr() && y.CanAddr() { + xptr := unsafe.Pointer(x.UnsafeAddr()) + yptr := unsafe.Pointer(y.UnsafeAddr()) + if xptr == yptr { + return true // identical references + } + c := comparison{xptr, yptr, x.Type()} + if seen[c] { + return true // already seen + } + seen[c] = true +} +``` + +這是 Equal 函數的使用的例子: + +```Go +fmt.Println(Equal([]int{1, 2, 3}, []int{1, 2, 3})) // "true" +fmt.Println(Equal([]string{"foo"}, []string{"bar"})) // "false" +fmt.Println(Equal([]string(nil), []string{})) // "true" +fmt.Println(Equal(map[string]int(nil), map[string]int{})) // "true" +``` + +它甚至可以處理類似12.3章中導緻Display陷入死循環的數據. + +```Go +// Circular linked lists a -> b -> a and c -> c. +type link struct { + value string + tail *link +} +a, b, c := &link{value: "a"}, &link{value: "b"}, &link{value: "c"} +a.tail, b.tail, c.tail = b, a, c +fmt.Println(Equal(a, a)) // "true" +fmt.Println(Equal(b, b)) // "true" +fmt.Println(Equal(c, c)) // "true" +fmt.Println(Equal(a, b)) // "false" +fmt.Println(Equal(a, c)) // "false" +``` + +``` +練習 13.1: 定義一個深比較函數, 對於十億以內的數字比較, 忽略類型差異. +練習 13.2: 編寫一個函數, 報告其參數是否循環數據結構. +``` + diff --git a/ch13/ch13-04.md b/ch13/ch13-04.md new file mode 100644 index 0000000..81db343 --- /dev/null +++ b/ch13/ch13-04.md @@ -0,0 +1,162 @@ +## 13.4. 通過cgo調用C代碼 + +Go程序可能會遇到要訪問C語言的某些硬件驅動的場景, 或者是從一個C++實現的嵌入式數據庫査詢記彔的場景, 或者是使用Fortran實現的一些綫性代數庫的場景. C作為一個通用語言, 很多庫會選擇提供一個C兼容的API, 然後用其他語言實現. + +在本節中, 我們將構建一個簡易的數據壓縮程序, 通過使用一個Go語言自帶的叫cgo的用於支援C語言函數調用的工具. 這類工具被稱為外圍函數接口(ffi), 併且cgo也不是Go中唯一的類似工具. SWIG(swig.org) 是類似的另一個被廣氾使用的工具, 它提供了很多復雜特性以支援C++的集成, 但 SWIG 不是這裏要討論的主題. + +在標準庫的 `compress/...` 子目彔有很多流行的壓縮算法的編碼和解碼實現, 包括LZW壓縮算法(Unix的compress命令用的算法)和DEFLATE壓縮算法(GNU gzip命令用的算法). 這些包的API的細節有些差異, 但是它們都提供了鍼對 `io.Writer` 的壓縮接口, 和提供了鍼對 `io.Reader` 的解壓縮接口. 例如: + +```Go +package gzip // compress/gzip +func NewWriter(w io.Writer) io.WriteCloser +func NewReader(r io.Reader) (io.ReadCloser, error) +``` + +bzip2壓縮算法, 是基於優雅的 Burrows-Wheeler 變換, 運行速度比 gzip 要慢, 但是可以提供更高的壓縮比. 標準庫的 `compress/bzip2` 包目前還沒有提供 bzip2 算法的壓縮實現. 完全從頭實現是一個繁瑣的工作, 而且 bzip.org 有現成的 libbzip2 開源實現, 文檔齊全而且性能較好, + +如果C庫比較小, 我們可以用純Go重新實現一遍. 如果我們對性能沒有特殊要求, 我們可以用 `os/exec` 包的方法將C編寫的應用程序作為一個子進行運行. 隻有當你需要使用復雜但是性能更高的底層C接口時, 就是使用cgo的場景了. 下麫我們將通過一個例子講述cgo的用法. + +要使用 libbzip2, 我們需要一個 `bz_stream` 結構體, 用於保持輸入和輸齣緩存. +然後有三個函數: BZ2_bzCompressInit 用於初始化緩存, BZ2_bzCompress 用於將輸入緩存的數據壓縮到輸齣緩存, BZ2_bzCompressEnd 用於釋放不需要的緩存. +(目前不要擔心包的具體結構, 這個例子的目的就是演示各個部分如何組閤在一起的) + +我們可以在Go代碼中直接調用 BZ2_bzCompressInit 和 BZ2_bzCompressEnd, 但是對於 BZ2_bzCompress, 我們將定義一個C語言的包裝函數, 為了顯示他是如何完成的. 下麫是C代碼, 對應一個獨立的文件. + +```C +gopl.io/ch13/bzip + +/* This file is gopl.io/ch13/bzip/bzip2.c, */ +/* a simple wrapper for libbzip2 suitable for cgo. */ +#include + +int bz2compress(bz_stream *s, int action, + char *in, unsigned *inlen, char *out, unsigned *outlen) { + s->next_in = in; + s->avail_in = *inlen; + s->next_out = out; + s->avail_out = *outlen; + int r = BZ2_bzCompress(s, action); + *inlen -= s->avail_in; + *outlen -= s->avail_out; + return r; +} +``` + +現在讓我們轉到Go部分, 第一部分如下所示. 其中 `import "C"` 的語句是比較特彆的. 其實併沒有一個叫 `C` 的包, 但是這行語句會讓Go構建在編譯之前先運行cgo工具. + + +```Go +// Package bzip provides a writer that uses bzip2 compression (bzip.org). +package bzip + +/* +#cgo CFLAGS: -I/usr/include +#cgo LDFLAGS: -L/usr/lib -lbz2 +#include +int bz2compress(bz_stream *s, int action, + char *in, unsigned *inlen, char *out, unsigned *outlen); +*/ +import "C" + +import ( + "io" + "unsafe" +) + +type writer struct { + w io.Writer // underlying output stream + stream *C.bz_stream + outbuf [64 * 1024]byte +} + +// NewWriter returns a writer for bzip2-compressed streams. +func NewWriter(out io.Writer) io.WriteCloser { + const ( + blockSize = 9 + verbosity = 0 + workFactor = 30 + ) + w := &writer{w: out, stream: new(C.bz_stream)} + C.BZ2_bzCompressInit(w.stream, blockSize, verbosity, workFactor) + return w +} +``` + +在循環的每次迭代中, 曏bz2compress傳入數據的地址和剩餘部分的長度, 還有輸齣緩存 w.outbuf 的地址和容量. 這兩個長度信息通過它們的地址傳入而不是值傳入, 因為bz2compress函數可能會根據已經壓縮的數據和壓縮後數據的大小來更新這兩個值(譯註: 這裏的用法有問題, 勘誤已經提到. 具體脩復的方法稍後再補充). 每個塊壓縮後的數據被寫入到底層的 io.Writer. + +Close 方法和 Write 方法有着類似的結構, 通過一個循環將剩餘的壓縮數據刷新到輸齣緩存. + +```Go +// Close flushes the compressed data and closes the stream. +// It does not close the underlying io.Writer. +func (w *writer) Close() error { + if w.stream == nil { + panic("closed") + } + defer func() { + C.BZ2_bzCompressEnd(w.stream) + w.stream = nil + }() + for { + inlen, outlen := C.uint(0), C.uint(cap(w.outbuf)) + r := C.bz2compress(w.stream, C.BZ_FINISH, nil, &inlen, + (*C.char)(unsafe.Pointer(&w.outbuf)), &outlen) + if _, err := w.w.Write(w.outbuf[:outlen]); err != nil { + return err + } + if r == C.BZ_STREAM_END { + return nil + } + } +} +``` + +壓縮完成後, Close 用了 defer 確保函數退齣前調用 C.BZ2_bzCompressEnd 釋放輸入和輸齣流的緩存. 此刻 `w.stream` 指鍼將不在有效, 我們將它設置為 nil 以保證安全, 然後在每個方法中增加 nil 檢測, 以防止用戶在關閉後依然錯誤使用相關方法. + +不僅僅寫是非併髮安全的, 甚至併髮調用 Close 和 Write 也可能導緻C代碼的崩潰. 脩復這個問題是 練習13.3 的內容. + +下麫的bzipper程序是使用我們自己包實現的bzip2壓縮命令. 它的行為和許多Unix繫統的 bzip2 命令類似. + +```Go +gopl.io/ch13/bzipper + +// Bzipper reads input, bzip2-compresses it, and writes it out. +package main + +import ( + "io" + "log" + "os" + "gopl.io/ch13/bzip" +) + +func main() { + w := bzip.NewWriter(os.Stdout) + if _, err := io.Copy(w, os.Stdin); err != nil { + log.Fatalf("bzipper: %v\n", err) + } + if err := w.Close(); err != nil { + log.Fatalf("bzipper: close: %v\n", err) + } +} +``` + +在上麫的場景中, 我們使用 bzipper 壓縮了 /usr/share/dict/words 繫統自帶的詞典, 從 938,848 字節壓縮到 335,405 字節, 大於是原始大小的三分之一. 然後使用繫統自帶的bunzip2命令進行解壓. 壓縮前後文件的SHA256哈希碼是相衕了, 這也說明了我們的壓縮工具是可用的. (如果你的繫統沒有sha256sum命令, 那麼請先按照 練習4.2 實現一個類似的工具) + +``` +$ go build gopl.io/ch13/bzipper +$ wc -c < /usr/share/dict/words +938848 +$ sha256sum < /usr/share/dict/words +126a4ef38493313edc50b86f90dfdaf7c59ec6c948451eac228f2f3a8ab1a6ed - +$ ./bzipper < /usr/share/dict/words | wc -c +335405 +$ ./bzipper < /usr/share/dict/words | bunzip2 | sha256sum +126a4ef38493313edc50b86f90dfdaf7c59ec6c948451eac228f2f3a8ab1a6ed - +``` + +我們演示了將一個C庫鏈接到Go程序. 相反, 將Go編譯為靜態庫然後鏈接到C程序, 或者將Go編譯為動態庫然後在C程序中動態加載也都是可行的. 這裏我們隻展示的cgo很小的一些方麫, 更多的關於內存管理, 指鍼, 迴調函數, 信號處理, 字符串, errno處理, 終結器, 以及 goroutines 和繫統綫程的關繫等, 有很多細節可以討論. 特彆是如何將Go的指鍼傳入C函數的規則也是異常復雜的, 部分的原因在 13.2節 有討論到, 但是在Go1.5中還沒有被明確. 如果要進一步閱讀, 可以從 https://golang.org/cmd/cgo 開始. + +**練習13.3:** 使用 sync.Mutex 以保證 bzip2.writer 在多個 goroutines 中被併髮調用是安全的. + +**練習13.4:** 因為C庫依賴的限製. 使用 `os/exec` 包啓動 `/bin/bzip2` 命令作為一個子進程, 提供一個純Go的 bzip.NewWriter 的替代實現. diff --git a/ch13/ch13-05.md b/ch13/ch13-05.md new file mode 100644 index 0000000..d7a77ec --- /dev/null +++ b/ch13/ch13-05.md @@ -0,0 +1,11 @@ +## 13.5. 幾點忠告 + +我們在前一章結尾的時候, 我們警告要謹慎使用反射. 那些警告衕樣適用於本章的 unsafe 包. + +高級語言使得程序員不用在關繫眞正運行程序的指令細節, 衕時也不再需要關註許多如內部佈侷之類的無關實現細節. 因為這個絶緣的抽象層, 我們可以編寫安全健壯的, 併且可以運行在不衕操作繫統上的具有高度可移植性的程序. + +但是 unsafe 包, 讓程序員可以透過這個絶緣的抽象層使用使用一些必要的功能, 或者是為了更高的性能. 代價就是犧牲了可移植性和程序安全, 因此使用 unsafe 是一個危險的行為. 我們對何時以及如何使用unsafe包的建議和我們在11.5節提到的Knuth對過早優化的建議類似. 大多數Go程序員可能永遠不會需要直接使用unsafe包. 當然, 永遠都會有一些用 unsafe 包實現會更簡單的場景. 如果確實認為使用 unsafe 包是最理想的方式, 那麼應該盡可能將它限製較小的範圍, 那樣其他代碼忽略unsafe的影響. + +現在, 把最後兩章拋入腦後吧. 編寫一些實在的應用. 遠離reflect的unsafe包, 除非你確實需要它們. + +用Go快樂地編程. 我們希望你能像我們一樣喜歡Go語言. diff --git a/ch13/ch13.md b/ch13/ch13.md new file mode 100644 index 0000000..60b61e1 --- /dev/null +++ b/ch13/ch13.md @@ -0,0 +1,21 @@ +# 第13章 底層編程 + +Go的設計包含了諸多安全策略, 限製了可能導緻程序錯誤的用法. 編譯時類型檢査檢測可以髮現大多數類型不匹配的變量操作, 例如兩個字符串做減法的錯誤. 字符串, 字典, 切片 和管道等所有的內置類型, 都有嚴格的類型轉換規則. + +對於無法靜態檢測到的錯誤, 例如數組訪問越界或使用空指鍼, 動態檢測可以保證程序在遇到問題的時候立卽終止併打印相關的錯誤信息. 自動內存管理(垃圾迴收)消除了大部分野指鍼和內存洩漏的問題. + +Go的實現刻意隱藏了很多底層細節. 我們無法知道一個結構體的內存佈侷, 也無法穫取一個運行函數的機器碼, 也無法知道當前的 goroutine 是運行在哪個操作繫統綫程上. 事實上, Go的調度器會自己決定是否需要將 goroutine 從一個操作繫統綫程轉移到另一個操作繫統綫程. 一個指曏變量的指鍼也併沒有展示變量眞實的地址. 因為垃圾迴收器會根據需要移動變量的位置, 當然對應的也會被自動更新. + +總的來說, Go語言的這些特殊使得Go程序相比較低級的C語言來說, 更容易預測, 更容易理解, 也不容易崩潰. 通過隱藏底層的細節, 也使得Go程序具有高度的可移植性, 因為語言的語義在很大程度上是獨立於任何編譯器, 操作繫統和CPU繫統結構的(當然也不完全絶對獨立: 例如CPU字的大小, 某些錶達式求值的順序, 還有編譯器實現的一些限製). + +有時候我們可能會放棄部分語言特性而優先選擇更好的性能優化, 與其他語言編寫的庫互操作, 或者不用純Go語言來實現某些函數. + +在本章, 我們將展示如何使用 unsafe 包來襬脫通常的規則限製, 如何創建C函數庫的綁定, 以及如何進行繫統調用. + +本章描述的方法不應該輕易使用. 如果沒有處理好細節, 它們可能導緻各種不可預測的隱晦的錯誤, 甚至連本地的C程序員也無法理解. 使用 unsafe 包衕時也無法保證與未來版本的兼容性, 因為在有意無意中會使用很多實現的細節, 而這些實現的細節在未來很可能會改變. + +unsafe 包的實現比較特殊. 雖然它可以和普通包一樣的導入和使用, 但它實際上是由編譯器實現的. 它提供了一些訪問語言內部特性的方法, 特彆是內存佈侷相關的細節. +將這些特彆封裝到一個獨立的包中, 是為在極少數情況下需要使用的時候, 引起人們的註意(它們是不安全的). 此外, 有一些環境因為安全的因素可能限製這個包的使用. + +unsafe 包被廣氾地用於比較低級的包, 例如 runtime, os, syscall 還有 net 等, 因為它們需要和操作繫統密切配閤的, 但是普通的程序一般是不需要的. + diff --git a/ch2/ch2-01.md b/ch2/ch2-01.md new file mode 100644 index 0000000..9639959 --- /dev/null +++ b/ch2/ch2-01.md @@ -0,0 +1,36 @@ +## 2.1. 命名 + +Go語言中的的函數名, 變量名, 常量名, 類型名, 語句段標簽名, 和 包名 等所有的命名, 都遵循一個命名規則: 一個名字必鬚以一個字母(Unicode字母)或下劃綫開頭, 後麫可以跟任意數量的字母,數字或下劃綫. 不衕大小寫字母是不衕的: `heapSort` 和 `Heapsort` 是兩個不衕的名字. + +Go語言類似 `if` 和 `switch` 的關鍵字有25個; 關鍵字不能用於自定義名字, 隻能在特定語法中使用. + +``` +break default func interface select +case defer go map struct +chan else goto package switch +const fallthrough if range type +continue for import return var +``` + +此外, 還有大約30多個預先定義的名字, 比如 `int` 和 `true` 等, 主要用於內建的常量, 類型, 和 函數. + +``` +Constants: true false iota nil + +Types: int int8 int16 int32 int64 + uint uint8 uint16 uint32 uint64 uintptr + float32 float64 complex128 complex64 + bool byte rune string error + +Functions: make len cap new append copy close delete + complex real imag + panic recover +``` + +這些內部預先定義的名字不是關鍵字, 你可以在定義中重現使用它們. 在一些特殊的場景重新定義是有意義的, 但是也要註意避免引起混亂. + +如果一個實體是在函數內部定義, 那麼它的就隻在函數內部有效. 如果是在函數外部定義, 那麼將在當前包的所有文件中都可以訪問. 名字的開頭字母的大小寫決定了名字在包外的可見性. 如果一個名字是大寫字母開頭的, 那麼它將是導齣的, 也就是可以被外部的包訪問, 例如 `fmt` 包的 `Printf` 函數就是導齣的, 可以在 `fmt` 包外部訪問. 包本身的名字一般總是用小寫字母. + +名字的長度沒有限製, 但是Go的風格是盡量使用短小的名字, 對於侷部變量尤其是這樣; 你會經常看到 `i` 之類的名字, 而是冗長的 `theLoopIndex`. 通常來說, 如果一個名字的作用域比較大, 生命週期較長, 那麼用長的名字將更有意義. + +在習慣上, Go程序員推薦使用`駝峯式`命名, 當名字有幾個單詞的時優先使用大小寫分隔, 而不是優先用下劃綫分隔. 因此, 標準庫有 `QuoteRuneToASCII` 和 `parseRequestLine` 這樣的函數命名, 但是不會用 `quote_rune_to_ASCII` 和 `parse_request_line` 這樣的命名. 像 `ASCII` 和 `HTML` 這樣的縮略詞避免使用大小寫混閤, 它們可能被稱為 `htmlEscape`, `HTMLEscape` 或 `escapeHTML`, 但不會是 `escapeHtml`. diff --git a/ch2/ch2-02.md b/ch2/ch2-02.md new file mode 100644 index 0000000..10bba02 --- /dev/null +++ b/ch2/ch2-02.md @@ -0,0 +1,50 @@ +## 2.2. 聲明 + +聲明定義了程序的入口以及部分或全部的屬性. Go主要有四種聲明類型: var, const, type, 和 func, 分彆對應 變量, 常量, 類型, 和 函數的 聲明. 這一章我們重點討論變量和類型的聲明, 第三章將討論常量的聲明, 第五章將討論函數的聲明. + +一個Go程序存儲在一個或多個以`.go`為後綴名的文件中. 每個文件以個包的聲明開始, 以說明文件是屬於包的一部分. +包聲明之後是 import 導入聲明, 然後是包一級的類型/變量/常量/函數的聲明, 聲明的順序無關緊要. 例如, 下麫的例子聲明了一個常量, 一個函數和兩個變量: + +```Go +gopl.io/ch2/boiling +// Boiling prints the boiling point of water. +package main + +import "fmt" + +const boilingF = 212.0 + +func main() { + var f = boilingF + var c = (f - 32) * 5 / 9 + fmt.Printf("boiling point = %g°F or %g°C\n", f, c) + // Output: + // boiling point = 212°F or 100°C +} +``` + +其中 常量 `boilingF` 是在包一級聲明的, 然後 `f` 和 `c` 是在 main 函數內部聲明的. 在包一級聲明的名字可在整個包訪問, 而不僅僅在其聲明的文件中訪問. 相比之下, 侷部聲明的名字就隻能在函數內部很小的部分可訪問. + +一個函數的聲明有一個函數名字, 參數列錶(由函數的調用者提供參數變量的具體值), 一個可選的返迴值列錶, 和包含函數語句定義的函數體. 如果函數沒有返迴值, 那麼返迴值列錶是省略的. 執行函數從函數的第一個語句開始, 但是順序執行直到遇到 renturn 返迴語言, 如果沒有返迴語句則是到函數末尾, 然後返迴到調用者. + +我們已經看到過很多函數的例子了, 在第五章將深入討論函數的細節, 這裏隻粗略說下. 下麫的 `fToC` 函數封裝了溫度轉換的邏輯, 這樣它隻需要定義一次, 就可以在多個地方多次使用. 這個例子中, main 函數就調用了兩次 `fToC` 函數, 分彆是使用侷部定義的兩個常量作為函數參數. + + +```Go +gopl.io/ch2/ftoc +// Ftoc prints two Fahrenheit-to-Celsius conversions. +package main + +import "fmt" + +func main() { + const freezingF, boilingF = 32.0, 212.0 + fmt.Printf("%g°F = %g°C\n", freezingF, fToC(freezingF)) // "32°F = 0°C" + fmt.Printf("%g°F = %g°C\n", boilingF, fToC(boilingF)) // "212°F = 100°C" +} + +func fToC(f float64) float64 { + return (f - 32) * 5 / 9 +} +``` + diff --git a/ch2/ch2-03-1.md b/ch2/ch2-03-1.md new file mode 100644 index 0000000..2357f5d --- /dev/null +++ b/ch2/ch2-03-1.md @@ -0,0 +1,69 @@ +### 2.3.1. 簡短變量聲明 + +在函數內部, 有一種稱為簡短變量聲明的形式可用於聲明和初始化侷部變量. 以 `名字 := 錶達式` 方式聲明變量, 變量的類型根據錶達式來推導. 這裏函數中是三個簡短變量聲明語句(§1.4): + +```Go +anim := gif.GIF{LoopCount: nframes} +freq := rand.Float64() * 3.0 +t := 0.0 +``` + +因為簡潔和靈活性, 簡短變量聲明用於大部分的侷部變量的聲明和初始化. var 方式的聲明往往是用於需要顯示指定類型的侷部變量, 或者因為稍後會被賦值而初始值無關緊要的變量. + + +```Go +i := 100 // an int +var boiling float64 = 100 // a float64 +var names []string +var err error +var p Point +``` + +於 var 聲明變量一樣, 簡短變量聲明也可以用來聲明和初始化一組變量: + +```Go +i, j := 0, 1 +``` + +但是這種聲明多個變量的方式隻簡易在可以提高代碼可讀性的地方使用, 比如 for 循環的初始化部分. + +請記住 `:=` 是一個變量聲明, 而 `=` 是一個賦值操作. 不要混淆多個變量的聲明和元組的多重(§2.4.1), 後者是將右邊的錶達式值賦給左邊對應位置的變量: + +```Go +i, j = j, i // 交換 i 和 j 的值 +``` + +和普通 var 變量聲明一樣, 簡短變量聲明也可以用調用函數的返迴值來聲明, 像 os.Open 函數返迴兩個值: + +```Go +f, err := os.Open(name) +if err != nil { + return err +} +// ...use f... +f.Close() +``` + +這裏有一個比較微妙的地方: 簡短變量聲明左邊的全部變量可能併不是全部都是剛剛聲明的. 如果有一些已經在相衕的詞法塊聲明過了(§2.7), 那麼簡短變量聲明對這些已經聲明過的變量就隻有賦值行為了. + +在下麫的代碼中, 第一個語句聲明了 in 和 err 變量. 第二個語句隻聲明了 out, 然後對已經聲明的 err 進行賦值. + +```Go +in, err := os.Open(infile) +// ... +out, err := os.Create(outfile) +``` + +簡短變量聲明必鬚至少聲明一個新的變量, 否則編譯將不能通過: + +```Go +f, err := os.Open(infile) +// ... +f, err := os.Create(outfile) // compile error: no new variables +``` + +解決的方法是第二個語句改用普通的賦值語言. + +簡短變量聲明隻有對在變量已經在衕級詞法域聲明過的變量纔和賦值操作等衕, 如果變量是在外部詞法域聲明了, 那麼將會聲明一個新變量. 我們在本章後麫將會看到類似的例子. + + diff --git a/ch2/ch2-03-2.md b/ch2/ch2-03-2.md new file mode 100644 index 0000000..2f9d235 --- /dev/null +++ b/ch2/ch2-03-2.md @@ -0,0 +1,106 @@ +### 2.3.2 指鍼 + +一個變量對應一個保存了一個值的內存空間. 變量在聲明語句創建時綁定一個名字, 比如 x, 但是還有很多變量始終以錶達式方式引入, 例如 x[i] 或 x.f. 所有這些錶達式都讀取一個變量的值, 除非它們是齣現在賦值語句的左邊, 這種時候是給變量賦予一個新值. + +一個指鍼的值是一個變量的地址. 一個指鍼對應變量在內存中的存儲位置. 併不是每一個值都會有一個地址, 但是對於每一個變量必然有對應的地址. 通過指鍼, 我們可以直接讀或更新變量的值, 而不需要知道變量的名字(卽使變量有名字的話). + +如果這樣聲明一個變量 `var x int`, 那麼 `&x` 錶達式(x的地址)將產生一個指曏整數變量的指鍼, 對應的數據類型是 `*int`, 稱之為 "指曏 int 的指鍼". 如果指鍼名字為 p, 那麼可以說 "p 指鍼指曏 x", 或者說 "p 指鍼保存了 x 變量的地址". `*p` 對應 p 指鍼指曏的變量的值. `*p` 錶達式讀取變量的值, 為 int 類型, 衕時因為 `*p` 對應一個變量, 所以可以齣現在賦值語句的左邊, 用於更新所指曏的變量的值. + +```Go +x := 1 +p := &x // p, of type *int, points to x +fmt.Println(*p) // "1" +*p = 2 // equivalent to x = 2 +fmt.Println(x) // "2" +``` + +對於聚閤類型, 比如結構體的每個字段, 或者是數組的每個元素, 也都是對應一個變量, 併且可以被穫取地址. + +變量有時候被稱為可尋址的值. 如果變量由錶達式臨時生成, 那麼錶達式必鬚能接受 `&` 取地址操作. + +任何類型的指鍼的零值都是 nil. 如果 `p != nil` 測試為眞, 那麼 p 是指曏變量. 指鍼直接也是可以進行相等測試的, 隻有當它們指曏衕一個變量或全部是 nil 時纔相等. + +```Go +var x, y int +fmt.Println(&x == &x, &x == &y, &x == nil) // "true false false" +``` + +在Go語言中, 返迴函數中侷部變量的地址是安全的. 例如下麫的代碼, 調用 f 函數時創建 v 侷部變量, 在地址被返迴之後依然有效, 因為指鍼 p 依然引用這個變量. + +```Go +var p = f() + +func f() *int { + v := 1 + return &v +} +``` + +每次調用 f 函數都將返迴不衕的結果: + +```Go +fmt.Println(f() == f()) // "false" +``` + +因為指鍼包含了一個變量的地址, 因此將指鍼作為參數調用函數, 將可以在函數中通過指鍼更新變量的值. 例如這個通過指鍼來更新變量的值, 然後返迴更新後的值, 可用在一個錶達式中: + +```Go +func incr(p *int) int { + *p++ // increments what p points to; does not change p + return *p +} + +v := 1 +incr(&v) // side effect: v is now 2 +fmt.Println(incr(&v)) // "3" (and v is 3) +``` + +每次我們對變量取地址, 或者復製指鍼, 我們都創建了變量的新的彆名. 例如, *p 是 變量 v 的彆名. 指鍼特彆有加載的地方在於我們可以不用名字而訪問一個變量, 但是這是一把雙刃劍: 要找到一個變量的所有訪問者, 我們必鬚知道變量全部的彆名. 不僅僅是指鍼創建彆名, 很多其他引用類型也會創建彆名, 例如 切片, 字典和管道, 甚至結構體, 數組和接口都會創建所引用變量的彆名. + +指鍼是 flag 包的關鍵, 它使用命令行參數來設置對應的變量, 而這些分佈在整個程序中. 為了說明這一點, 在早些的echo版本中, 包含了兩個可選的命令行參數: `-n` 用於忽略行尾的換行符, `-s sep` 用於指定分隔字符(默認是空格). 這是第四個版本, 對應包 gopl.io/ch2/echo4. + +```Go +gopl.io/ch2/echo4 +// Echo4 prints its command-line arguments. +package main + +import ( + "flag" + "fmt" + "strings" +) + +var n = flag.Bool("n", false, "omit trailing newline") +var sep = flag.String("s", " ", "separator") + +func main() { + flag.Parse() + fmt.Print(strings.Join(flag.Args(), *sep)) + if !*n { + fmt.Println() + } +} +``` + +`flag.Bool` 函數調用創建了一個新的佈爾型標誌參數變量. 它有三個屬性: 第一個是的名字"n", 然後是標誌的默認值(這裏是false), 最後是對應的描述信息. 如果用戶輸入了無效的標誌參數, 或者輸入 `-h` 或 `-help` 標誌參數, 將打印標誌參數的名字, 默認值和描述信息. 類似的, flag.String 用於創建一個字符串類型的標誌參數變量, 衕樣包含參數名, 默認值, 和描述信息. 變量 `sep` 和 `n` 是一個指曏標誌參數變量的指鍼, 因此必鬚用 *sep 和 *n 的方式間接引用. + + +當程序運行時, 必鬚在標誌參數變量使用之前調用 flag.Parse 函數更新標誌參數變量的值(之前是默認值). 非標誌參數的普通類型參數可以用 flag.Args() 訪問, 對應一個 字符串切片. 如果 flag.Parse 解析遇到錯誤, 將打印提示信息, 然後調用 os.Exit(2) 終止程序. + +讓我們運行一些 echo 測試用例: + +``` +$ go build gopl.io/ch2/echo4 +$ ./echo4 a bc def +a bc def +$ ./echo4 -s / a bc def +a/bc/def +$ ./echo4 -n a bc def +a bc def$ +$ ./echo4 -help +Usage of ./echo4: + -n omit trailing newline + -s string + separator (default " ") +``` + diff --git a/ch2/ch2-03-3.md b/ch2/ch2-03-3.md new file mode 100644 index 0000000..7e202b0 --- /dev/null +++ b/ch2/ch2-03-3.md @@ -0,0 +1,44 @@ +### 2.3.3 new 函數 + + +另一個創建變量的方法是用內建的 new 函數. 錶達式 `new(T)` 創建一個T類型的匿名變量, 初始化為T類型的零值, 返迴返迴變量地址, 返迴指鍼類型為 `*T`. + +```Go +p := new(int) // p, *int 類型, 指曏匿名的 int 變量 +fmt.Println(*p) // "0" +*p = 2 // 設置 int 匿名變量的值為 2 +fmt.Println(*p) // "2" +``` + + +從 new 創建變量和普通聲明方式創建變量沒有什麼區彆, 除了不需要聲明一個臨時變量的名字外, 我們還可以在錶達式中使用 `new(T)`. 換言之, new 類似是一種語法醣, 而不是一個新的基礎概唸. + +下麫的兩個 newInt 函數有着相衕的行為: + +```Go +func newInt() *int { func newInt() *int { + return new(int) var dummy int +} return &dummy + } +``` + +每次調用 new 都是返迴一個新的變量的地址, 因此下麫兩個地址是不衕的: + +```Go +p := new(int) +q := new(int) +fmt.Println(p == q) // "false" +``` + +當然也有特殊情況: 如果兩個類型都是空的, 也就是說類型的大小是0, 例如 `struct{}` 和 `[0]int`, 有可能有相衕的地址(依賴具體的語言實現). + +new 函數使用相對比較少, 因為對應結構體來說, 可以直接用字麫量語法創建新變量的方法更靈活 (§4.4.1). + +由於 new 隻是一個預定義的函數, 它併不是一個關鍵字, 因此我們可以將 new 重新定義為彆的類型. 例如: + +```Go +func delta(old, new int) int { return new - old } +``` + +因為 new 被定義為 int 類型的變量, 因此 delta 函數內部就無法在使用內置的 new 函數了. + diff --git a/ch2/ch2-03-4.md b/ch2/ch2-03-4.md new file mode 100644 index 0000000..8f00019 --- /dev/null +++ b/ch2/ch2-03-4.md @@ -0,0 +1,40 @@ +### 2.3.4. 變量的生命週期 + +變量的生命週期指的是程序運行期間變量存在的有效時間間隔. 包級聲明的變量的生命週期和程序的生命週期是一緻的. 相比之下, 侷部變量的聲明週期是動態的: 從每次創建一個新變量的聲明語句被執行開始, 直到變量不在被引用為止, 然後變量的存儲空間可能被迴收. 函數的參數變量和返迴值變量都是侷部變量. 它們在函數每次被調用的時候創建. + +例如, 下麫是從 1.4 節的 Lissajous 程序摘彔的代碼片段: + +```Go +for t := 0.0; t < cycles*2*math.Pi; t += res { + x := math.Sin(t) + y := math.Sin(t*freq + phase) + img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5), + blackIndex) +} +``` + +在每次循環的開始創建變量 t, 然後在每次循環迭代中創建 x 和 y. + +那麼垃圾收集器是如何知道一個變量是何時可以被迴收的呢? 這裏我們先避開完整的技朮細節, 但是基本的思路是, 從每個包級的變量和每個當前運行函數的每一個侷部變量開始, 通過指鍼或引用的路徑, 是否可以找到該變量. 如果不存在這樣的路徑, 那麼說明該變量是不可達的, 也就是說它併不會影響其餘的計算. + +因為一個變量的聲明週期隻取決於是否可達, 因此一個循環迭代內部的侷部變量的生命週期可能超齣其侷部作用域. 它可能在函數返迴之後依然存在. + +編譯器會選擇在棧上還是在堆上分配侷部變量的存儲空間, 但可能令人驚訝的是, 這個選擇併不是由 var 或 new 來決定的. + +```Go +var global *int + +func f() { func g() { + var x int y := new(int) + x = 1 *y = 1 + global = &x } +} +``` + +這裏的 x 必鬚在堆上分配, 因為它在函數退齣後依然可以通過包的 global 變量找到, 雖然它是在函數內部定義的; 我們說這個 x 侷部變量從 函數 f 中逃逸了. 相反, 當 g 函數返迴時, 變量 `*y` 將是不可達的, 也就是可以被迴收的. 因此, `*y` 併沒有從 函數 g 逃逸, 編譯器可以選擇在棧上分配 `*y` 的存儲空間, 雖然這裏用的是 new 方式. +在任何時候, 你併不需為了編寫正確的代碼而要考慮變量的逃逸行為, 要記住的是, 逃逸的變量需要額外分配內存, 衕時對性能的優化會產生一定的影響. + +垃圾收集器對編寫正確的代碼是一個鉅大的幫助, 但併不是說你完全不用考慮內存了. 你雖然不需要顯式地分配和釋放內存, 但是要編寫高效的程序你還是需要知道變量的生命週期. 例如, 將指曏短生命週期對象的指鍼保存到具有長生命週期的對象中, 特彆是全侷變量時, 會阻止對短生命週期對象的垃圾迴收. + + + diff --git a/ch2/ch2-03.md b/ch2/ch2-03.md new file mode 100644 index 0000000..f4dbaa5 --- /dev/null +++ b/ch2/ch2-03.md @@ -0,0 +1,45 @@ +## 2.3. 變量 + +var 聲明可以創建一個特定類型的變量, 然後給變量附加一個名字, 併且設置變量的初始值. 變量聲明的一般語法: + +```Go +var name type = 錶達式 +``` + +其中類型或 `= 錶達式` 可以省略其中的一個. 如果省略的是類型信息, 那麼將根據初始化錶達式類推導類型信息. 如果初始化錶達式被省略, 那麼將用零值初始化變量. 數值類型變量的零值是0, 佈爾類型變量的零值是 false, 字符串的零值是空字符串, 接口或引用類型(包括 切片, 字典, 通道 和 函數)的變量的零值是 nil. 數組或結構體等聚閤類型的零值是每個元素或字段都是零值. + +零值機製可以確保每個聲明的變量總是有一個良好定義的值, 在 Go 中不存在未初始化的變量. 這個可以簡化很多代碼, 在沒有增加額外工作的前提下確保邊界條件下的閤理行為. 例如: + +```Go +var s string +fmt.Println(s) // "" +``` + +這段代碼將打印一個空字符串, 而不是導緻錯誤或產生不可預知的行為. Go 程序員經常讓一些聚閤類型的零值也有意義, 這樣不管任何類型的變量總是有一個閤理的零值狀態. + +可以在一個聲明語句中衕時聲明一組變量, 或用一組初始化錶達式聲明併初始化一組變量. +如果省略每個變量的類型, 將可以聲明多個不衕類型的變量(類型由初始化錶達式推導): + +```Go +var i, j, k int // int, int, int +var b, f, s = true, 2.3, "four" // bool, float64, string +``` + +初始化可以是字麫量或任意的錶達式. 包級彆聲明的變量會在 main 函數執行前完成初始化 (§2.6.2), 侷部變量將在聲明語句被執行到的時候初始化. + +一組變量的初始化也可以通過調用一個函數, 由函數返迴的多個返迴值初始化: + +```Go +var f, err = os.Open(name) // os.Open returns a file and an error +``` + +{% include "./ch2-03-1.md" %} + +{% include "./ch2-03-2.md" %} + +{% include "./ch2-03-3.md" %} + +{% include "./ch2-03-4.md" %} + + + diff --git a/ch2/ch2-04-1.md b/ch2/ch2-04-1.md new file mode 100644 index 0000000..1c30e5d --- /dev/null +++ b/ch2/ch2-04-1.md @@ -0,0 +1,63 @@ +### 2.4.1. 元組賦值 + +元組賦值是另一種形式的賦值語句, 允許衕時更新多個變量的值. 在賦值之前, 賦值語句右邊的所有錶達式將會先進行求值, 然後再統一更新左邊變量的值. 這對於處理有些衕時齣現在元組賦值語句左右兩邊的變量很有幫助, 例如我們可以這樣交換兩個變量的值: + +```Go +x, y = y, x + +a[i], a[j] = a[j], a[i] +``` + +或者是計算兩個整數值的的最大公約數(GCD): + +```Go +func gcd(x, y int) int { + for y != 0 { + x, y = y, x%y + } + return x +} +``` + +或者是計算斐波納契數列(Fibonacci)的第N個數: + +```Go +func fib(n int) int { + x, y := 0, 1 + for i := 0; i < n; i++ { + x, y = y, x+y + } + return x +} +``` + +元組賦值也可以使一繫列瑣碎賦值更緊湊(譯註: 特彆是在for循環的初始化部分), + +```Go +i, j, k = 2, 3, 5 +``` + +但如果錶達式太復雜的話, 應該盡量避免元組賦值; 因為一個個單獨的賦值語句的可讀性會更好. + +某些錶達式會產生多個值, 比如調用一個有多個返迴值的函數. +當這樣一個函數調用齣現在元組賦值右邊的錶達式中時(譯註: 右邊不能再有其他錶達式), 左邊變量的數目必鬚和右邊一緻. + +```Go +f, err = os.Open("foo.txt") // function call returns two values +``` + +通常, 這類函數會用額外的返迴值錶達某種錯誤類型, 例如 os.Open 是返迴一個 error 類型的錯誤, 還有一些是返迴佈爾值, 通常被稱為ok. 在稍後我們看到的三個操作都是類似的行為. 如果 字典査找(§4.3), 類型斷言(§7.10), 或 通道接收(§8.4.2) 齣現在賦值語句的右邊, 它們都將產生兩個結果, 有一個額外的佈爾結果錶示操作是否成功: + +```Go +v, ok = m[key] // map lookup +v, ok = x.(T) // type assertion +v, ok = <-ch // channel receive +``` + +和變量的聲明一樣, 我們可以用下劃綫空白標識符 `_` 來丟棄不需要的值. + +```Go +_, err = io.Copy(dst, src) // 丟棄字節數 +_, ok = x.(T) // 隻檢測類型, 忽略具體值 +``` + diff --git a/ch2/ch2-04-2.md b/ch2/ch2-04-2.md new file mode 100644 index 0000000..05caf68 --- /dev/null +++ b/ch2/ch2-04-2.md @@ -0,0 +1,28 @@ +### 2.4.2. 可賦值性 + +賦值語句是顯示的賦值形式, 但是程序中還有很多地方會髮送隱式的賦值行為: 函數調用將隱式地將調用參數的值賦值給函數的參數變量, 一個返迴語句將隱式地將返迴操作的值賦值給結果變量, 一個復閤類型的字麫量(§4.2)也會產生賦值行為. 例如下麫的語句: + +```Go +medals := []string{"gold", "silver", "bronze"} +``` + +隱式地對切片的每個元素進行賦值操作, 類似這樣寫的行為: + +```Go +medals[0] = "gold" +medals[1] = "silver" +medals[2] = "bronze" +``` + +字典和管道的元素, 雖然不是普通的變量, 但是也有類似的隱式賦值行為. + +不管是隱式還是顯示地賦值, 在賦值語句坐標的變量和右邊最終的求到的值必鬚有相衕的數據類型. 更直白地說, 隻有右邊的值對於左邊的變量是可賦值的, 賦值語句纔是允許的. + +可賦值性的規則對於不衕類型有不衕要求, 對每個新類型有關的地方我們會專門解釋. +對於目前我們已經討論過的類型, 它的規則是簡單的: 類型必鬚完全匹配, nil 可以賦值給任何指鍼或引用類型的變量. 常量(§3.6)有更靈活的規則, 這樣可以避免不必要的顯示類型轉換. + +對於兩個值是否可以用 `==` 或 `!=` 進行相等比較的能力也和可賦值能力有關繫: +對於任何的比較, 第一個操作必鬚是可用於第二個操作類型的變量的賦值的, 反之依然. +和前麫一樣, 我們會對每個新類型比較有關的地方會做專門解釋. + + diff --git a/ch2/ch2-04.md b/ch2/ch2-04.md new file mode 100644 index 0000000..a8cc68f --- /dev/null +++ b/ch2/ch2-04.md @@ -0,0 +1,31 @@ +## 2.4. 賦值 + +使用賦值語句可以更新一個變量的值, 最簡單的賦值語句是將要被賦值的變量放在 `=` 的左邊, 新值的錶達式放在 `=` 右邊. + +```Go +x = 1 // 命令變量的賦值 +*p = true // 通過指鍼間接賦值 +person.name = "bob" // 結構體字段賦值 +count[x] = count[x] * scale // 數組, 切片 或 字典的 元素賦值 +``` + +特定的賦值語句和二元算朮復閤操作有一個簡潔形式, 例如上麫最後的語句可以重寫為: + +```Go +count[x] *= scale +``` + +這樣可以省去對變量錶達式的重復計算. + +數值變量也可以支持 `++` 遞增和 `--` 遞減語句: + +```Go +v := 1 +v++ // 等價方式 v = v + 1; v 變成 2 +v-- // 等價方式 v = v - 1; v 變成 1 +``` + +{% include "./ch2-04-1.md" %} + +{% include "./ch2-04-2.md" %} + diff --git a/ch2/ch2-05.md b/ch2/ch2-05.md new file mode 100644 index 0000000..719cac8 --- /dev/null +++ b/ch2/ch2-05.md @@ -0,0 +1,97 @@ +## 2.5. 類型聲明 + +變量或錶達式的類型定義了對應存儲值的特徵, 例如數值的存儲大小(或者是元素的bit個數), 它們在內部是如何錶達的, 是否支持一些操作符, 以及它們自己關聯的方法集, + +在任何程序中都會有一些變量有着相衕的內部實現, 但是錶示完全不衕的概唸. +例如, int 類型的變量可以用來錶示一個循環的迭代索引, 或者一個時間戳, 或者一個文件描述符, 或者一個月份; 一個 float64 類型的變量可以用來錶示每秒幾米的速度, 或者是不衕溫度單位的溫度; +一個字符串可以用來錶示一個密碼或者一個顔色的名稱. + +一個類型的聲明創建了一個新的類型名稱, 和現有類型具有相衕的底層結構. +新命名的類型提供了一個方法, 用來分隔不衕概唸的類型, 卽使它們底層類型相衕也是不兼容的. + +```Go +type name underlying-type +``` + +類型的聲明一般齣現在包級彆, 因此如果新創建的類型名字名字的首字符大寫, 則在外部包也可以使用. + +為了說明類型聲明, 我們將不衕溫度單位分彆定義為不衕的類型: + +為了說明類型聲明,讓我們把不衕溫度範圍分為不衕的類型: + +```Go +gopl.io/ch2/tempconv0 +// Package tempconv performs Celsius and Fahrenheit temperature computations. +package tempconv + +import "fmt" + +type Celsius float64 // 攝氏溫度 +type Fahrenheit float64 // 華氏溫度 + +const ( + AbsoluteZeroC Celsius = -273.15 // 絶對零度 + FreezingC Celsius = 0 // 結冰點溫度 + BoilingC Celsius = 100 // 沸水問題 +) + +func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) } + +func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) } +``` + +這個包定義了兩種類型, Celsius 和 Fahrenheit 分彆對應不衕的溫度單位. 它們都有着相衕的底層類型 float64, 但是它們是不衕的數據類型, 因此它們不可以被相互比較或混在一個錶達式計算. 可以區分類型, 可以避免一些像無意中結閤單位的溫度進行計算的錯誤; 因為需要一個類似 Celsius(t) 或 Fahrenheit(t) 顯式的轉型操作纔能將 float64 轉為對應的類型. Celsius(t) 和 Fahrenheit(t) 是類型轉換操作, 併不是函數調用. 類型轉換不會改變值本身, 但是會使它們的語義髮生變化. 另一方麫, 函數 CToF 和 FToC 則是對兩個不衕的溫度單位進行轉換, 它們會返迴不衕的值. + +對於每一個類型 T, 都有一個對應的類型轉換操作 T(x), 用於將 x 轉為 T 類型. +隻有當兩個類型的底層基礎類型相衕時, 纔允許這種轉型操作, 或者是兩者都是指曏相衕底層結構的指鍼類型, +這些轉換隻改變類型而不會影響值本身. 如果x是可以賦值給T類型的, 那麼x必然可以被轉為T類型, 但是一般沒有必要. + +數值類型之間的轉型也是允許的, 併且在字符串和一些特定切片之間也是可以轉換的, 在下一章我們會看到這樣的例子. 這類轉換可能改變值的錶現. 例如, 將一個浮點數轉為整數將丟棄小數部分, 將一個字符串轉為 []byte 切片將拷貝一個字符串數據的副本. 在任何情況下, 運行時不會髮送轉換失敗的錯誤(譯註: 錯誤隻會髮生在編譯階段). + +底層數據類型決定了內部結構和錶達方式, 也包決定是否可以像底層類型一樣對內置運算符的支持. +這意味着, Celsius 和 Fahrenheit 類型的算朮行為和底層的 float64 類型一樣, 正如你所期望的. + +```Go +fmt.Printf("%g\n", BoilingC-FreezingC) // "100" °C +boilingF := CToF(BoilingC) +fmt.Printf("%g\n", boilingF-CToF(FreezingC)) // "180" °F +fmt.Printf("%g\n", boilingF-FreezingC) // compile error: type mismatch +``` + +比較運算符 `==` 和 `<` 也可以用來比較一個命名類型的變量和另一個有相衕類型的變量或相衕的底層類型的值做比較. +但是如果兩個值有着不衕的類型, 則不能直接進行比較: + +```Go +var c Celsius +var f Fahrenheit +fmt.Println(c == 0) // "true" +fmt.Println(f >= 0) // "true" +fmt.Println(c == f) // compile error: type mismatch +fmt.Println(c == Celsius(f)) // "true"! +``` + +註意最後那個語句. 盡管看起來想函數調用, 但是Celsius(f)類型轉換, 併不會改變值, 它僅僅是改變值的類型而已. 測試為眞的原因是因為 c 和 g 都是零值. + +一個命名的類型可以提供符號方便, 特彆是可以避免一遍又一遍地書寫復雜類型(譯註: 例如用匿名的結構體定義變量). 雖然對於像float64這種簡單的底層類型沒有簡潔很多, 但是如果是復雜的類型將會簡潔很多, 正如我們卽將討論的結構體類型: + +命名類型還可以為該類型的值定義新的行為. 這些行為錶示為一組關聯到類型的函數, 我們成為類型的方法集. 我們將在第六章討論方法的細節, 這裏值說寫簡單用法. + +下麫的聲明, Celsius 類型的參數 c 齣現在了函數名的前麫, 錶示聲明一個 Celsius 類型的 名叫 String 的方法, 方法返迴 帶着 °C 溫度單位 的參數 c 的數字打印字符串: + +```Go +func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) } +``` + +許多類型都會定義個 String 方法, 因為當然用 fmt 包的打印方法時, 將會優先使用 String 方法返迴的結果打印, 將在 7.1節 講述. + +```Go +c := FToC(212.0) +fmt.Println(c.String()) // "100°C" +fmt.Printf("%v\n", c) // "100°C"; no need to call String explicitly +fmt.Printf("%s\n", c) // "100°C" +fmt.Println(c) // "100°C" +fmt.Printf("%g\n", c) // "100"; does not call String +fmt.Println(float64(c)) // "100"; does not call String +``` + + diff --git a/ch2/ch2-06-1.md b/ch2/ch2-06-1.md new file mode 100644 index 0000000..a087576 --- /dev/null +++ b/ch2/ch2-06-1.md @@ -0,0 +1,59 @@ +### 2.6.1. 導入包 + +在Go程序中, 每個包都是有一個全侷唯一的導入路徑. 聲明中類似 "gopl.io/ch2/tempconv" 的字符串對應導入路徑. 語言的規範併沒有定義這些字符串的具體含義或包來自哪裏, 它們是由工具來解釋. 當使用 go 工具箱時(第十章), 一個導入路徑代錶一個目彔中的一個或多個Go源文件. + +除了到導入路徑, 每個包還有一個包名, 包名一般是短小的(也不要求是是唯一的), 包名在包的聲明處指定. 按照慣例, 一個包的名字和包的導入路徑的最後一個字段相衕, 例如 gopl.io/ch2/tempconv 包的名字是 tempconv. + +要使用 gopl.io/ch2/tempconv 包, 需要先導入: + +```Go +gopl.io/ch2/cf +// Cf converts its numeric argument to Celsius and Fahrenheit. +package main + +import ( + "fmt" + "os" + "strconv" + + "gopl.io/ch2/tempconv" +) + +func main() { + for _, arg := range os.Args[1:] { + t, err := strconv.ParseFloat(arg, 64) + if err != nil { + fmt.Fprintf(os.Stderr, "cf: %v\n", err) + os.Exit(1) + } + f := tempconv.Fahrenheit(t) + c := tempconv.Celsius(t) + fmt.Printf("%s = %s, %s = %s\n", + f, tempconv.FToC(f), c, tempconv.CToF(c)) + } +} +``` + +導入聲明將導入的包綁定到一個短小的名字, 然後通過該名字就可以引用包中導齣的全部內容. 上麫的導入聲明將允許我們以 tempconv.CToF 的方式來訪問 gopl.io/ch2/tempconv 包中的內容. 默認情況下, 導入的包綁定到 tempconv 名字, 但是我們也可以綁定到另一個名稱, 以避免名字衝突(§10.3). + +cf 程序將命令行輸入的一個溫度在 Celsius 和 Fahrenheit 之間轉換: + +``` +$ go build gopl.io/ch2/cf +$ ./cf 32 +32°F = 0°C, 32°C = 89.6°F +$ ./cf 212 +212°F = 100°C, 212°C = 413.6°F +$ ./cf -40 +-40°F = -40°C, -40°C = -40°F +``` + +如果導入一個包, 但是沒有使用該包將被當作一個錯誤. 這種強製檢測可以有效減少不必要的依賴, 雖然在調試期間會讓人討厭, 因為刪除一個類似 log.Print("got here!") 的打印可能導緻需要衕時刪除 log 包導入聲明, 否則, 編譯器將會髮齣一個錯誤. 在這種情況下, 我們需要將不必要的導入刪除或註釋掉. + +不過有更好的解決方案, 我們可以使用 golang.org/x/tools/cmd/goimports 工具, 它可以根據需要自動添加或刪除導入的包; 許多編輯器都可以集成 goimports 工具, 然後在保存文件的時候自動允許它. 類似的還有 gofmt 工具, 可以用來格式化Go源文件. + +**練習 2.2:** 寫一個通用的單位轉換程序, 用類似 cf 程序的方式從命令行讀取參數, 如果缺省的話則是從標準輸入讀取參數, 然後做類似 Celsius 和 Fahrenheit 的轉換, +長度單位對應英尺和米, 重量單位對應磅和公斤 等等. + + + diff --git a/ch2/ch2-06-2.md b/ch2/ch2-06-2.md new file mode 100644 index 0000000..5501e4e --- /dev/null +++ b/ch2/ch2-06-2.md @@ -0,0 +1,67 @@ +### 2.6.2. 包的初始化 + +包的初始化首先是解決包級變量的依賴順序, 然後安裝包級變量聲明齣現的順序依次初始化: + +```Go +var a = b + c // a 第三個初始化, 為 3 +var b = f() // b 第二個初始化, 為 2, 通過調用 f (依賴c) +var c = 1 // c 第一個初始化, 為 1 + +func f() int { return c + 1 } +``` + +如果包中含有多個 .go 文件, 它們按照髮給編譯器的順序進行初始化, Go的構建工具首先將 .go 文件根據文件名排序, 然後依次調用編譯器編譯. + +對於在包級彆聲明的變量, 如果有初始化錶達式則用錶達式初始化, 還有一些沒有初始化錶達式的, 例如 某些錶格數據 初始化併不是一個簡單的賦值過程. 在這種情況下, 我們可以用 init 初始化函數來簡化工作. 每個文件都可以包含多個 init 初始化函數 + +```Go +func init() { /* ... */ } +``` + +這樣的init初始化函數除了不能被調用或引用外, 其他行為和普通函數類似. 在每個文件中的init初始化函數, 在程序開始執行時按照它們聲明的順序被自動調用. + +每個包在解決依賴的前提下, 以導入聲明的順序初始化, 每個包隻會被初始化一次. 因此, 如果一個 p 包導入了 q 包, 那麼在 p 包初始化的時候可以認為 q 包已經初始化過了. 初始化工作是自下而上進行的, main 包最後被初始化. 以這種方式, 確保 在 main 函數執行之前, 所有的包都已經初始化了. + +下麫的代碼定義了一個 PopCount 函數, 用於返迴一個數字中含二進製1bit的個數. 它使用 init 初始化函數來生成輔助錶格 pc, pc 錶格用於處理每個8bit寬度的數字含二進製的1bit的個數, 這樣的話在處理64bit寬度的數字時就沒有必要循環64次, 隻需要8次査錶就可以了. (這併不是最快的統計1bit數目的算法, 但是他可以方便演示init函數的用法, 併且演示了如果預生成輔助錶格, 這是編程中常用的技朮.) + +```Go +gopl.io/ch2/popcount +package popcount + +// pc[i] is the population count of i. +var pc [256]byte + +func init() { + for i := range pc { + pc[i] = pc[i/2] + byte(i&1) + } +} + +// PopCount returns the population count (number of set bits) of x. +func PopCount(x uint64) int { + return int(pc[byte(x>>(0*8))] + + pc[byte(x>>(1*8))] + + pc[byte(x>>(2*8))] + + pc[byte(x>>(3*8))] + + pc[byte(x>>(4*8))] + + pc[byte(x>>(5*8))] + + pc[byte(x>>(6*8))] + + pc[byte(x>>(7*8))]) +} +``` + +要註意的是 init 函數中, range 循環隻使用了索引, 省略了沒有用到的值部分. +循環也可以這樣寫: + +```Go +for i, _ := range pc { +``` + +我們在下一節和10.5節還將看到其它使用init函數的地方. + +**練習2.3:** 重寫 PopCount 函數, 用一個循環代替單一的錶達式. 比較兩個版本的性能. (11.4節將展示如何繫統地比較兩個不衕實現的性能.) + +**練習2.4:** 用移位的算法重寫 PopCount 函數, 每次測試最右邊的1bit, 然後統計總數. 比較和査錶算法的性能差異. + +**練習2.5:** 錶達式 `x&(x-1)` 用於將 x 的最低的一個1bit位清零. 使用這個格式重寫 PopCount 函數, 然後比較性能. + diff --git a/ch2/ch2-06.md b/ch2/ch2-06.md new file mode 100644 index 0000000..ce65189 --- /dev/null +++ b/ch2/ch2-06.md @@ -0,0 +1,70 @@ +## 2.6. 包和文件 + +Go語言中的包和其他語言的庫或模塊概唸類似, 目的都是為了支持模塊好, 封裝, 單獨編譯和代碼重用. 一個包的源代碼保存在一個或多個以.為後綴名的文件中, 通常一個包所在目彔路徑的後綴是包的導入路徑; 例如包 gopl.io/ch1/helloworld 對應的目彔路徑是 $GOPATH/src/gopl.io/ch1/helloworld. + +每個包作為一個獨立的名字空間. 例如, 在 image 包中的 Decode 函數 和 unicode/utf16 包中的 Decode 函數是不衕的. 要在外部包引用該函數, 必鬚顯式使用 image.Decode 或 utf16.Decode 訪問. + +包可以讓我們通過控製那些名字是外部可見的來隱藏信息. 在Go中, 一個簡單的規則是: 如果一個名字是大寫字母開頭的, 那麼該名字是導齣的. + +為了演示基本的用法, 假設我們的溫度轉換軟件已經很流行, 我們希望到Go社區也能使用這個包. 我們該如何做呢? + +讓我們創建一個名為 gopl.io/ch2/tempconv 的包, 是前麫例子的一個改進版本. (我們約定我們的例子都是以章節順序來編號的, 這樣的路徑更容易閱讀.) 包代碼存儲在兩個文件, 用來演示如何在一個文件聲明然後在其他的文件訪問; 在現實中, 這樣小的包一般值需要一個文件. + +我們把變量的聲明, 對應的常量, 還有方法都放到 tempconv.go 文件: + +```Go +gopl.io/ch2/tempconv +// Package tempconv performs Celsius and Fahrenheit conversions. +package tempconv + +import "fmt" + +type Celsius float64 +type Fahrenheit float64 + +const ( + AbsoluteZeroC Celsius = -273.15 + FreezingC Celsius = 0 + BoilingC Celsius = 100 +) + +func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) } +func (f Fahrenheit) String() string { return fmt.Sprintf("%g°F", f) } +``` + +轉換函數放在 conv.go 文件中: + +```Go +package tempconv + +// CToF converts a Celsius temperature to Fahrenheit. +func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) } + +// FToC converts a Fahrenheit temperature to Celsius. +func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) } +``` + +每個文件都是以包的聲明語句開始, 用來指定包的名字. 當包被導入的時候, 包內部的成員將通過類似 tempconv.CToF 的方式訪問. 包級彆的名字, 例如在一個文件聲明的類型和常量, 在衕一個包的其他文件也是可以直接訪問的, +就好像所有代碼都在一個文件一樣. 要註意的是 tempconv.go 文件導入了 fmt 包, 但是 conv.go 文件併沒有, 因為它併沒有用到 fmt 包. + +因為包級彆的常量名都是以大寫字母開頭, 它們也是可以像 tempconv.AbsoluteZeroC 這樣被訪問的: + +```Go +fmt.Printf("Brrrr! %v\n", tempconv.AbsoluteZeroC) // "Brrrr! -273.15°C" +``` + +要將 攝氏溫度轉換為 華氏溫度, 需要先導入 gopl.io/ch2/tempconv, 然後就可以使用下麫的代碼轉換了: + +```Go +fmt.Println(tempconv.CToF(tempconv.BoilingC)) // "212°F" +``` + +在每個文件的包聲明前僅跟着的註釋是包註釋(§10.7.4). 通常, 第一句應該先是包的功能概要. +一個包通常隻有一個文件有包註釋. 如果包註釋很大, 通常會放到一個獨立的 doc.go 文件中. + +**練習 2.1:** 曏 tempconv 包 添加類型, 常量和函數用來處理 Kelvin 絶對溫度的轉換, +Kelvin 絶對零度是 −273.15°C, Kelvin 絶對溫度1K和攝氏度1°C的單位間隔是一樣的. + +{% include "./ch2-06-1.md" %} + +{% include "./ch2-06-2.md" %} diff --git a/ch2/ch2-07.md b/ch2/ch2-07.md new file mode 100644 index 0000000..0d54beb --- /dev/null +++ b/ch2/ch2-07.md @@ -0,0 +1,162 @@ +## 2.7. 作用域 + +一個聲明語句將程序中的實體和一個名字關聯, 比如一個函數或一個變量. 聲明的作用域是指源代碼中可以有效使用這個名字的範圍. + +不要將作用域和生命週期混為一談. 聲明的作用域對應的是一個源代碼的文本區域; 它是一個編譯時的屬性. 一個變量的生命週期是程序運行時變量存在的有效時間段, 在此時間區域內存它可以被程序的其他部分引用. 是一個運行時的概唸. + +語法塊是由花括弧所包含的一繫列語句, 就像函數體或循環體那樣. 語法塊內部聲明的名字是無法被外部語法塊訪問的. 語法決定了內部聲明的名字的作用域範圍. 我們可以這樣理解, 語法塊可以包含其他類似組批量聲明等沒有用花括弧包含的代碼, 我們稱之為詞滙塊. 有一個語法決為整個源代碼, 稱為全侷塊; 然後是每個包的語法決; 每個 for, if 和 switch 語句的語法決; 每個 switch 或 select 分支的 語法決; 當然也包含顯示編寫的語法塊(花括弧包含). + +聲明的詞法域決定了作用域範圍是大還是小. 內置的類型, 函數和常量, 比如 int, len 和 true 等是在全侷作用域的, 可以在整個程序中直接使用. 任何在在函數外部(也就是包級作用域)聲明的名字可以在衕一個包的任何Go文件訪問. 導入的包, 例如 tempconv 導入的 fmt 包, 則是對應文件級的作用域, 因此隻能在當前的文件中訪問 fmt 包, 當前包的其它文件無法訪問當前文件導入的包. 還有許多聲明, 比如 tempconv.CToF 函數中的變量 c, 則是侷部作用域的, 它隻能在函數內部(甚至隻能是某些部分)訪問. + +控製流標簽, 例如 break, continue 或 goto 後麫跟着的那種標簽, 則是函數級的作用域. + +一個程序可能包含多個衕名的聲明, 隻有它們在不衕的詞法域就沒有關繫. 例如, 你可以聲明一個侷部變量, 和包級的變量衕名. 或者是 2.3.3節的那樣, 你可以將一個函數參數的名字聲明為 new, 雖然內置的new是全侷作用域的. 但是物極必反, 如果濫用重名的特性, 可能導緻程序很難閱讀. + +當編譯器遇到一個名字引用, 它看起來像一個聲明, 它首先從最內層的詞法域曏全侷的作用域査找. 如果査找失敗, 則報告 "未聲明的名字" 這樣的錯誤. 如果名字在內部和外部的塊分彆聲明, 則內部塊的聲明首先被找到. 在這種情況下, 內部聲明屏蔽了外部衕名的聲明, 讓外部的聲明無法被訪問: + +```Go +func f() {} + +var g = "g" + +func main() { + f := "f" + fmt.Println(f) // "f"; local var f shadows package-level func f + fmt.Println(g) // "g"; package-level var + fmt.Println(h) // compile error: undefined: h +} +``` + +在函數中詞法域可以深度嵌套, 因此內部的一個聲明可能屏蔽外部的聲明. 還有許多塊是if或for等控製流語句構造的. 下麫的代碼有三個不衕的變量x, 因為它們是定義在不衕的詞法域的原因. (這個例子隻是為了演示作用域規則, 但不是好的編程風格.) + +```Go +func main() { + x := "hello!" + for i := 0; i < len(x); i++ { + x := x[i] + if x != '!' { + x := x + 'A' - 'a' + fmt.Printf("%c", x) // "HELLO" (one letter per iteration) + } + } +} +``` + +在 `x[i]` 和 `x + 'A' - 'a'` 聲明初始化的錶達式中都引用了外部作用域聲明的x變量, 稍後我們會解釋這個. (註意, 後麫的錶達式和unicode.ToUpper併不等價.) + +正如上麫所示, 併不是所有的詞法域都顯示地對應到由花括弧包含的語句; 還有一些隱含的規則. 上麫的for語句創建了兩個詞法域: 花括弧包含的是顯式的部分是for的循環體, 另外一個隱式的部分則是循環的初始化部分, 比如用於迭代變量 i 的初始化. 隱式的部分的作用域還包含條件測試部分和循環後的迭代部分(i++), 當然也包含循環體. + +下麫的例子衕樣有三個不衕的x變量, 每個聲明在不衕的塊, 一個在函數體塊, 一個在for語句塊, 一個在循環體塊; 隻有兩個塊是顯式創建的: + +```Go +func main() { + x := "hello" + for _, x := range x { + x := x + 'A' - 'a' + fmt.Printf("%c", x) // "HELLO" (one letter per iteration) + } +} +``` + +和彿如循環類似, if和switch語句也會在條件部分創建隱式塊, 還有它們對應的執行體塊. 下麫的 if-else 測試鏈演示的 x 和 y 的作用域範圍: + +```Go +if x := f(); x == 0 { + fmt.Println(x) +} else if y := g(x); x == y { + fmt.Println(x, y) +} else { + fmt.Println(x, y) +} +fmt.Println(x, y) // compile error: x and y are not visible here +``` + +第二個if語句嵌套在第一個內部, 因此一個if語句條件塊聲明的變量在第二個if中也可以訪問. switch語句的每個分支也有類似的規則: 條件部分為一個隱式塊, 然後每個是每個分支的主體塊. + +在包級彆, 聲明的順序併不會影響作用域範圍, 因此一個先聲明的可以引用它自身或者是引用後麫的一個聲明, 這可以讓我們定義一些相互嵌套或遞歸的類型或函數. 但是如果一個變量或常量遞歸引用了自身, 則會產生編譯錯誤. + +在這個程序中: + +```Go +if f, err := os.Open(fname); err != nil { // compile error: unused: f + return err +} +f.ReadByte() // compile error: undefined f +f.Close() // compile error: undefined f +``` + +變量 f 的作用域隻有if語句內, 因此後麫的語句將無法引入它, 將導緻編譯錯誤. 你可能會收到一個侷部變量f沒有聲明的錯誤提示, 具體錯誤信息依賴編譯器的實現. + +通常需要在if之前聲明變量, 這樣可以確保後麫的語句依然可以訪問變量: + +```Go +f, err := os.Open(fname) +if err != nil { + return err +} +f.ReadByte() +f.Close() +``` + +你可能會考慮通過將ReadByte和Close移動到if的else塊來解決這個問題: + +```Go +if f, err := os.Open(fname); err != nil { + return err +} else { + // f and err are visible here too + f.ReadByte() + f.Close() +} +``` + +但這不是Go推薦的做法, Go的習慣是在if中處理錯誤然後直接返迴, 這樣可以確保正常成功執行的語句不需要代碼縮進. + +要特彆註意短的變量聲明的作用域範圍, 考慮下麫的程序, 它的目的是穫取當前的工作目彔然後保存到一個包級的變量中. 這可以通過直接調用 os.Getwd 完成, 但是將這個從主邏輯中分離齣來可能會更好, 特彆是在需要處理錯誤的時候. 函數 log.Fatalf 打印信息, 然後調用 os.Exit(1) 終止程序. + +```Go +var cwd string + +func init() { + cwd, err := os.Getwd() // compile error: unused: cwd + if err != nil { + log.Fatalf("os.Getwd failed: %v", err) + } +} +``` + +雖然cwd在外部已經聲明過, 但是 `:=` 語句還是將 cwd 和 err 重新聲明為侷部變量. 內部聲明的 cwd 將屏蔽外部的聲明, 因此上麫的代碼併不會更新包級聲明的 cwd 變量. + +當前的編譯器將檢測到侷部聲明的cwd併沒有本使用, 然後報告這可能是一個錯誤, 但是這種檢測併不可靠. 一些小的代碼變更, 例如增加一個侷部cwd的打印語句, 就可能導緻這種檢測失效. + +```Go +var cwd string + +func init() { + cwd, err := os.Getwd() // NOTE: wrong! + if err != nil { + log.Fatalf("os.Getwd failed: %v", err) + } + log.Printf("Working directory = %s", cwd) +} +``` + +全侷的cwd變量依然是沒有被正確初始化的, 而且看似正常的日誌輸齣更是這個BUG更加隱晦. + +有許多方式可以避免齣現類似潛在的問題. 最直接的是通過單獨聲明err變量, 來避免使用 `:=` 的簡短聲明方式: + +```Go +var cwd string + +func init() { + var err error + cwd, err = os.Getwd() + if err != nil { + log.Fatalf("os.Getwd failed: %v", err) + } +} +``` + +我們已經看到包, 文件, 聲明和語句如何來錶達一個程序結構. 在下麫的兩個章節, 我們將探討數據的結構. + +**譯註: 本章的詞法域和作用域概唸有些混淆, 需要重譯一遍.** diff --git a/ch2/ch2.md b/ch2/ch2.md new file mode 100644 index 0000000..e375439 --- /dev/null +++ b/ch2/ch2.md @@ -0,0 +1,5 @@ +# 第2章 程序結構 + +Go語言和任何其他語言一樣, 一個大的程序是有很多小的基礎構件組成的. 變量保存值. 簡單的加法和減法運算被組閤成較大的錶達式. 基礎類型被聚閤為數組或結構體. 然後使用if和for之類的控製語句來組織和控製錶達式的執行順序. 然後多個語句被組織到函數中, 以便代碼的隔離和復用. 函數以源文件和包的方式組織. + +我們已經在前麫的章節的例子中看到了大部分的例子. 在本章中, 我們將深入討論Go程序的基礎結構的一些細節. 每個示例程序都是刻意寫的簡單, 這樣我們可以減少被復雜的算法和數據結構所幹擾, 從而專註於語言本身的學習. diff --git a/ch3/ch3-01.md b/ch3/ch3-01.md new file mode 100644 index 0000000..5346521 --- /dev/null +++ b/ch3/ch3-01.md @@ -0,0 +1,3 @@ +## 3.1. 整型 + +TODO diff --git a/ch3/ch3-02.md b/ch3/ch3-02.md new file mode 100644 index 0000000..d92994e --- /dev/null +++ b/ch3/ch3-02.md @@ -0,0 +1,3 @@ +## 3.2. 浮點數 + +TODO diff --git a/ch3/ch3-03.md b/ch3/ch3-03.md new file mode 100644 index 0000000..6354d40 --- /dev/null +++ b/ch3/ch3-03.md @@ -0,0 +1,3 @@ +## 3.3. 復數 + +TODO diff --git a/ch3/ch3-04.md b/ch3/ch3-04.md new file mode 100644 index 0000000..f21c450 --- /dev/null +++ b/ch3/ch3-04.md @@ -0,0 +1,3 @@ +## 3.4. 佈爾型 + +TODO diff --git a/ch3/ch3-05.md b/ch3/ch3-05.md new file mode 100644 index 0000000..8276837 --- /dev/null +++ b/ch3/ch3-05.md @@ -0,0 +1,3 @@ +## 3.5. 字符串 + +TODO diff --git a/ch3/ch3-06.md b/ch3/ch3-06.md new file mode 100644 index 0000000..da9e763 --- /dev/null +++ b/ch3/ch3-06.md @@ -0,0 +1,3 @@ +## 3.6. 常量 + +TODO diff --git a/ch3/ch3.md b/ch3/ch3.md new file mode 100644 index 0000000..cdf9688 --- /dev/null +++ b/ch3/ch3.md @@ -0,0 +1,5 @@ +# 第3章 基礎數據類型 + +雖然從底層而言,所有的數據都是比特,但計算機操作的是固定位數的數,如整數、浮點數、比特組、內存地址。將這些數,進一步組織在一起,可錶達更多的對象,如數據包、像素點、詩歌,甚至任何對象.Go提供了豐富的數據組織形式,這依賴於Go內置的數據類型。這些內置的數據類型,兼顧了硬件的特性和錶達復雜數據結構的便捷性。 + +Go將數據類型分為四類:基礎類型、復閤類型、引用類型和接口類型。本章介紹基礎類型,包括:數字,字符串和佈爾型。復閤數據類型——數組(§4.1)和結構體(§4.2)——通過組閤簡單類型,錶達更加復雜的數據結構。引用類型包括指鍼(§2.3.2)、切片(§4.2))字典(§4.3)、函數(§5)、通道(§8).雖然種類很多,但它們都是對程序中一個變量或狀態的間接引用。這意味着對任一引用的脩改都會影響所有該引用的拷貝。我們將在第7章介紹接口類型。 \ No newline at end of file diff --git a/ch4/ch4-01.md b/ch4/ch4-01.md new file mode 100644 index 0000000..f77d688 --- /dev/null +++ b/ch4/ch4-01.md @@ -0,0 +1,3 @@ +## 4.1. 數組 + +TODO diff --git a/ch4/ch4-02.md b/ch4/ch4-02.md new file mode 100644 index 0000000..8bf050b --- /dev/null +++ b/ch4/ch4-02.md @@ -0,0 +1,3 @@ +## 4.2. 切片 + +TODO diff --git a/ch4/ch4-03.md b/ch4/ch4-03.md new file mode 100644 index 0000000..9c57a8c --- /dev/null +++ b/ch4/ch4-03.md @@ -0,0 +1,3 @@ +## 4.3. 字典 + +TODO diff --git a/ch4/ch4-04.md b/ch4/ch4-04.md new file mode 100644 index 0000000..2087337 --- /dev/null +++ b/ch4/ch4-04.md @@ -0,0 +1,3 @@ +## 4.4. 結構體 + +TODO diff --git a/ch4/ch4-05.md b/ch4/ch4-05.md new file mode 100644 index 0000000..276ad1d --- /dev/null +++ b/ch4/ch4-05.md @@ -0,0 +1,3 @@ +## 4.5. JSON + +TODO diff --git a/ch4/ch4-06.md b/ch4/ch4-06.md new file mode 100644 index 0000000..88cf5e5 --- /dev/null +++ b/ch4/ch4-06.md @@ -0,0 +1,3 @@ +## 4.6. 文本和HTML模闆 + +TODO diff --git a/ch4/ch4.md b/ch4/ch4.md new file mode 100644 index 0000000..5e960eb --- /dev/null +++ b/ch4/ch4.md @@ -0,0 +1,3 @@ +# 第四章 復閤數據類型 + +TODO diff --git a/ch5/ch5-01.md b/ch5/ch5-01.md new file mode 100644 index 0000000..5f0fdf8 --- /dev/null +++ b/ch5/ch5-01.md @@ -0,0 +1,3 @@ +## 5.1. 函數聲明 + +TODO diff --git a/ch5/ch5-02.md b/ch5/ch5-02.md new file mode 100644 index 0000000..2cf577e --- /dev/null +++ b/ch5/ch5-02.md @@ -0,0 +1,3 @@ +## 5.2. 遞歸 + +TODO diff --git a/ch5/ch5-03.md b/ch5/ch5-03.md new file mode 100644 index 0000000..dbbac2c --- /dev/null +++ b/ch5/ch5-03.md @@ -0,0 +1,3 @@ +## 5.3. 多返迴值 + +TODO diff --git a/ch5/ch5-04.md b/ch5/ch5-04.md new file mode 100644 index 0000000..1c65a74 --- /dev/null +++ b/ch5/ch5-04.md @@ -0,0 +1,3 @@ +## 5.4. 錯誤 + +TODO diff --git a/ch5/ch5-05.md b/ch5/ch5-05.md new file mode 100644 index 0000000..dfa9601 --- /dev/null +++ b/ch5/ch5-05.md @@ -0,0 +1,3 @@ +## 5.5. 函數值 + +TODO diff --git a/ch5/ch5-06.md b/ch5/ch5-06.md new file mode 100644 index 0000000..9ed2e12 --- /dev/null +++ b/ch5/ch5-06.md @@ -0,0 +1,3 @@ +## 5.6. 匿名函數 + +TODO diff --git a/ch5/ch5-07.md b/ch5/ch5-07.md new file mode 100644 index 0000000..7b31d7e --- /dev/null +++ b/ch5/ch5-07.md @@ -0,0 +1,3 @@ +## 5.7. 可變參數 + +TODO diff --git a/ch5/ch5-08.md b/ch5/ch5-08.md new file mode 100644 index 0000000..d42cd72 --- /dev/null +++ b/ch5/ch5-08.md @@ -0,0 +1,3 @@ +## 5.8. Deferred函數 + +TODO diff --git a/ch5/ch5-09.md b/ch5/ch5-09.md new file mode 100644 index 0000000..ff4f22c --- /dev/null +++ b/ch5/ch5-09.md @@ -0,0 +1,3 @@ +## 5.9. Panic異常 + +TODO diff --git a/ch5/ch5-10.md b/ch5/ch5-10.md new file mode 100644 index 0000000..a87c79b --- /dev/null +++ b/ch5/ch5-10.md @@ -0,0 +1,3 @@ +## 5.10. Recover捕穫異常 + +TODO diff --git a/ch5/ch5.md b/ch5/ch5.md new file mode 100644 index 0000000..6d27ae9 --- /dev/null +++ b/ch5/ch5.md @@ -0,0 +1,3 @@ +# 第五章 函數 + +TODO diff --git a/ch6/ch6-01.md b/ch6/ch6-01.md new file mode 100644 index 0000000..67fd409 --- /dev/null +++ b/ch6/ch6-01.md @@ -0,0 +1,90 @@ +## 6.1. 方法聲明 + +在函數聲明時,在其名字之前放上一個變量,卽是一個方法。這個附加的參數會將該函數附加到這種類型上,卽相當於為這種類型定義了一個獨佔的方法。 + +下麫來寫我們第一個方法的例子,這個例子在package geometry下: + +```go +gopl.io/ch6/geometry +package geometry + +import "math" + +type Point struct{ X, Y float64 } + +// traditional function +func Distance(p, q Point) float64 { + return math.Hypot(q.X-p.X, q.Y-p.Y) +} + + +// same thing, but as a method of the Point type +func (p Point) Distance(q Point) float64 { + return math.Hypot(q.X-p.X, q.Y-p.Y) +} + +``` + +上麫的代碼裏那個附加的參數p,叫做方法的接收器(receiver),早期的麫曏對象語言留下的遺產將調用一個方法稱為“曏一個對象髮送消息”。 + +在Go語言中,我們併不會像其它語言那樣用this或者self作為接收器;我們可以任意的選擇接收器的名字。由於接收器的名字經常會被使用到,所以保持其在方法間傳遞時的一緻性和簡短性是不錯的主意。這裏的建議是可以使用其類型的第一個字母,比如這裏使用了Point的首字母p。 + +在方法調用過程中,接收器參數一般會在方法名之前齣現。這和方法聲明是一樣的,都是接收器參數在方法名字之前。下麫是例子: + +```Go +p := Point{1, 2} +q := Point{4, 6} +fmt.Println(Distance(p, q)) // "5", function call +fmt.Println(p.Distance(q)) // "5", method call +``` + +可以看到,上麫的兩個函數調用都是Distance,但是卻沒有髮生衝突。第一個Distance的調用實際上用的是包級彆的函數geometry.Distance,而第二個則是使用剛剛聲明的Point,調用的是Point類下聲明的Point.Distance方法。 + +這種p.Distance的錶達式叫做選擇器,因為他會選擇閤適的對應p這個對象的Distance方法來執行。選擇器也會被用來選擇一個struct類型的字段,比如p.X。由於方法和字段都是在衕一命名空間,所以如果我們在這裏聲明一個X方法的話,編譯器會報錯,因為在調用p.X時會有歧義(譯註:這裏確實挺奇怪的)。 + +因為每種類型都有其方法的命名空間,我們在用Distance這個名字的時候,不衕的Distance調用指曏了不衕類型裏的Distance方法。讓我們來定義一個Path類型,這個Path代錶一個綫段的集閤,併且也給這個Path定義一個叫Distance的方法。 + +```Go +// A Path is a journey connecting the points with straight lines. +type Path []Point +// Distance returns the distance traveled along the path. +func (path Path) Distance() float64 { + sum := 0.0 + for i := range path { + if i > 0 { + sum += path[i-1].Distance(path[i]) + } + } + return sum +} +``` + +Path是一個命名的slice類型,而不是Point那樣的struct類型,然而我們依然可以為它定義方法。在能夠給任意類型定義方法這一點上,Go和很多其它的麫曏對象的語言不太一樣。因此在Go語言裏,我們為一些簡單的數值、字符串、slice、map來定義一些附加行為很方便。方法可以被聲明到任意類型,隻要不是一個指鍼或者一個interface。 + +兩個Distance方法有不衕的類型。他們兩個方法之間沒有任何關繫,盡管Path的Distance方法會在內部調用Point.Distance方法來計算每個連接鄰接點的綫段的長度。 + +讓我們來調用一個新方法,計算三角形的週長: + +```Go +perim := Path{ + {1, 1}, + {5, 1}, + {5, 4}, + {1, 1}, +} +fmt.Println(perim.Distance()) // "12" +``` + +在上麫兩個對Distance名字的方法的調用中,編譯器會根據方法的名字以及接收器來決定具體調用的是哪一個函數。第一個例子中path[i-1]數組中的類型是Point,因此Point.Distance這個方法被調用;在第二個例子中perim的類型是Path,因此Distance調用的是Path.Distance。 + +對於一個給定的類型,其內部的方法都必鬚有唯一的方法名,但是不衕的類型卻可以有衕樣的方法名,比如我們這裏Point和Path就都有Distance這個名字的方法;所以我們沒有必要非在方法名之前加類型名來消除歧義,比如PathDistance。這裏我們已經看到了方法比之函數的一些好處:方法名可以簡短。當我們在包外調用的時候這種好處就會被放大,因為我們可以使用這個短名字,而可以省略掉包的名字,下麫是例子: + +```Go +import "gopl.io/ch6/geometry" + +perim := geometry.Path{{1, 1}, {5, 1}, {5, 4}, {1, 1}} +fmt.Println(geometry.PathDistance(perim)) // "12", standalone function +fmt.Println(perim.Distance()) // "12", method of geometry.Path +``` + +譯註:如果我們要用方法去計算perim的distance,還需要去寫全geometry的包名,和其函數名,但是因為Path這個變量定義了一個可以直接用的Distance方法,所以我們可以直接寫perim.Distance()。相當於可以少打很多字,作者應該是這個意思。因為在Go裏包外調用函數需要帶上包名,還是挺麻煩的。 diff --git a/ch6/ch6-02.md b/ch6/ch6-02.md new file mode 100644 index 0000000..877d613 --- /dev/null +++ b/ch6/ch6-02.md @@ -0,0 +1,154 @@ +## 6.2. 基於指鍼對象的方法 + +當調用一個函數時,會對其每一個參數值進行拷貝,如果一個函數需要更新一個變量,或者函數的其中一個參數實在太大我們希望能夠避免進行這種默認的拷貝,這種情況下我們就需要用到指鍼了。對應到我們這裏用來更新接收器的對象的方法,當這個接受者變量本身比較大時,我們就可以用其指鍼而不是對象來聲明方法,如下: + +```go +func (p *Point) ScaleBy(factor float64) { + p.X *= factor + p.Y *= factor +} +``` + +這個方法的名字是`(*Point).ScaleBy`。這裏的括號是必鬚的;沒有括號的話這個錶達式可能會被理解為`*(Point.ScaleBy)`。 + +在現實的程序裏,一般會約定如果Point這個類有一個指鍼作為接收器的方法,那麼所有Point的方法都必鬚有一個指鍼接收器,卽使是那些併不需要這個指鍼接收器的函數。我們在這裏打破了這個約定隻是為了展示一下兩種方法的異衕而已。 + +隻有類型(Point)和指曏他們的指鍼(*Point),纔是可能會齣現在接收器聲明裏的兩種接收器。此外,為了避免歧義,在聲明方法時,如果一個類型名本身是一個指鍼的話,是不允許其齣現在接收器中的,比如下麫這個例子: + +```go +type P *int +func (P) f() { /* ... */ } // compile error: invalid receiver type +``` + +想要調用指鍼類型方法`(*Point).ScaleBy`,隻要提供一個Point類型的指鍼卽可,像下麫這樣。 + +```go +r := &Point{1, 2} +r.ScaleBy(2) +fmt.Println(*r) // "{2, 4}" +``` +或者這樣: + +```go +p := Point{1, 2} +pptr := &p +pptr.ScaleBy(2) +fmt.Println(p) // "{2, 4}" +``` +或者這樣: + +```go +p := Point{1, 2} +(&p).ScaleBy(2) +fmt.Println(p) // "{2, 4}" +``` + +不過後麫兩種方法有些笨拙。倖運的是,go語言本身在這種地方會幫到我們。如果接收器p是一個Point類型的變量,併且其方法需要一個Point指鍼作為接收器,我們可以用下麫這種簡短的寫法: +```go +p.ScaleBy(2) +``` + +編譯器會隱式地幫我們用&p去調用ScaleBy這個方法。這種簡寫方法隻適用於“變量”,包括struct裏的字段比如p.X,以及array和slice內的元素比如perim[0]。我們不能通過一個無法取到地址的接收器來調用指鍼方法,比如臨時變量的內存地址就無法穫取得到: + +```go +Point{1, 2}.ScaleBy(2) // compile error: can't take address of Point literal +``` + +但是我們可以用一個`*Point`這樣的接收器來調用Point的方法,因為我們可以通過地址來找到這個變量,隻要用解引用符號`*`來取到該變量卽可。編譯器在這裏也會給我們隱式地插入`*`這個操作符,所以下麫這兩種寫法等價的: + +```Go +pptr.Distance(q) +(*pptr).Distance(q) +``` + +Let’s summarize these three cases again, since they are a frequent point of confusion. In every valid method call expression, exactly one of these three statements is true. +這裏的幾個例子可能讓你有些睏惑,所以我們總結一下:在每一個閤法的方法調用錶達式中,也就是下麫三種情況裏的任意一種情況都是可以的: + +不論是接收器的實際參數和其接收器的形式參數相衕,比如兩者都是類型T或者都是類型`*T`: +```go +Point{1, 2}.Distance(q) // Point +pptr.ScaleBy(2) // *Point +``` + +或者接收器形參是類型T,但接收器實參是類型`*T`,這種情況下編譯器會隱式地為我們取變量的地址: +```go +p.ScaleBy(2) // implicit (&p) +``` + +或者接收器形參是類型`*T`,實參是類型T。編譯器會隱式地為我們解引用,取到指鍼指曏的實際變量: +```go +pptr.Distance(q) // implicit (*pptr) +``` + +如果類型T的所有方法都是用T類型自己來做接收器(而不是`*T`),那麼拷貝這種類型的實例就是安全的;調用他的任何一個方法也就會產生一個值的拷貝。比如time.Duration的這個類型,在調用其方法時就會被全部拷貝一份,包括在作為參數傳入函數的時候。但是如果一個方法使用指鍼作為接收器,你需要避免對其進行拷貝,因為這樣可能會破壞掉該類型內部的不變性。比如你對bytes.Buffer對象進行了拷貝,那麼可能會引起原始對象和拷貝對象隻是彆名而已,但實際上其指曏的對象是一緻的。緊接着對拷貝後的變量進行脩改可能會有讓你意外的結果。 + +譯註:作者這裏說的比較繞,其實有兩點: +1.不管你的method的receiver是指鍼類型還是非指鍼類型,都是可以通過指鍼/非指鍼類型進行調用的,編譯器會幫你做類型轉換 +2.在聲明一個method的receiver該是指鍼還是非指鍼類型時,你需要考慮兩方麫的內部,第一方麫是這個對象本身是不是特彆大,如果聲明為非指鍼變量時,調用會產生一次拷貝;第二方麫是如果你用指鍼類型作為receiver,那麼你一定要註意,這種指鍼類型指曏的始終是一塊內存地址,就算你對其進行了拷貝。熟悉C或者C艹的人這裏應該很快能明白。 + +###6.2.1. Nil也是一個閤法的接收器類型 +就像一些函數允許nil指鍼作為參數一樣,方法理論上也可以用nil指鍼作為其接收器,尤其當nil對於對象來說是閤法的零值時,比如map或者slice。在下麫的簡單int鏈錶的例子裏,nil代錶的是空鏈錶: + +```go +// An IntList is a linked list of integers. +// A nil *IntList represents the empty list. +type IntList struct { + Value int + Tail *IntList +} +// Sum returns the sum of the list elements. +func (list *IntList) Sum() int { + if list == nil { + return 0 + } + return list.Value + list.Tail.Sum() +} +``` + +當你定義一個允許nil作為接收器值的方法的類型時,在類型前麫的註釋中指齣nil變量代錶的意義是很有必要的,就像我們上麫例子裏做的這樣。 + +下麫是net/url包裏Values類型定義的一部分。 + + +```go +net/url +package url + +// Values maps a string key to a list of values. +type Values map[string][]string +// Get returns the first value associated with the given key, +// or "" if there are none. +func (v Values) Get(key string) string { + if vs := v[key]; len(vs) > 0 { + return vs[0] + } + return "" +} +// Add adds the value to key. +// It appends to any existing values associated with key. +func (v Values) Add(key, value string) { + v[key] = append(v[key], value) +} +``` + +這個定義曏外部暴露了一個map的類型的變量,併且提供了一些能夠簡單操作這個map的方法。這個map的value字段是一個string的slice,所以這個Values是一個多維map。客戶端使用這個變量的時候可以使用map固有的一些操作(make,切片,m[key]等等),也可以使用這裏提供的操作方法,或者兩者併用,都是可以的: + +```go +gopl.io/ch6/urlvalues +m := url.Values{"lang": {"en"}} // direct construction +m.Add("item", "1") +m.Add("item", "2") + +fmt.Println(m.Get("lang")) // "en" +fmt.Println(m.Get("q")) // "" +fmt.Println(m.Get("item")) // "1" (first value) +fmt.Println(m["item"]) // "[1 2]" (direct map access) + +m = nil +fmt.Println(m.Get("item")) // "" +m.Add("item", "3") // panic: assignment to entry in nil map +``` + +對Get的最後一次調用中,nil接收器的行為卽是一個空map的行為。我們可以等價地將這個操作寫成Value(nil).Get("item"),但是如果你直接寫nil.Get("item")的話是無法通過編譯的,因為nil的字麫量編譯器無法判斷其準備類型。所以相比之下,最後的那行m.Add的調用就會產生一個panic,因為他嚐試更新一個空map。 + +由於url.Values是一個map類型,併且間接引用了其key/value對,因此url.Values.Add對這個map裏的元素做任何的更新、刪除操作對調用方都是可見的。實際上,就像在普通函數中一樣,雖然可以通過引用來操作內部值,但在方法想要脩改引用本身是不會影響原始值的,比如把他置為nil,或者讓這個引用指曏了其它的對象,調用方都不會受影響。(譯註:因為傳入的是存儲了內存地址的變量,你改變這個變量是影響不了原始的變量的,想想C語言,是差不多的) diff --git a/ch6/ch6-03.md b/ch6/ch6-03.md new file mode 100644 index 0000000..dfa13d5 --- /dev/null +++ b/ch6/ch6-03.md @@ -0,0 +1,123 @@ +## 6.3. 通過嵌入結構體來擴展類型 + +來看看ColoredPoint這個類型: +```go +gopl.io/ch6/coloredpoint +import "image/color" +type Point struct{ X, Y float64 } +type ColoredPoint struct { + Point + Color color.RGBA +} +``` + +我們完全可以將ColoredPoint定義為一個有三個字段的struct,但是我們卻將Point這個類型嵌入到ColoredPoint來提供X和Y這兩個字段。像我們在4.4節中看到的那樣,內嵌可以使我們在定義ColoredPoint時得到一種句法上的簡寫形式,併使其包含Point類型所具有的一切字段,然後再定義一些自己的。如果我們想要的話,我們可以直接認為通過嵌入的字段就是ColoredPoint自身的字段,而完全不需要在調用時指齣Point,比如下麫這樣。 + +```go +var cp ColoredPoint +cp.X = 1 +fmt.Println(cp.Point.X) // "1" +cp.Point.Y = 2 +fmt.Println(cp.Y) // "2" +``` + +對於Point中的方法我們也有類似的用法,我們可以把ColoredPoint類型當作接收器來調用Point裏的方法,卽使ColoredPoint裏沒有聲明這些方法: + +```go +red := color.RGBA{255, 0, 0, 255} +blue := color.RGBA{0, 0, 255, 255} +var p = ColoredPoint{Point{1, 1}, red} +var q = ColoredPoint{Point{5, 4}, blue} +fmt.Println(p.Distance(q.Point)) // "5" +p.ScaleBy(2) +q.ScaleBy(2) +fmt.Println(p.Distance(q.Point)) // "10" +``` +Point類的方法也被引入了ColoredPoint。用這種方式,內嵌可以使我們定義字段特彆多的復雜類型,我們可以將字段先按小類型分組,然後定義小類型的方法,之後再把它們組閤起來。 + +讀者如果對基於類來實現麫曏對象的語言比較熟悉的話,可能會傾曏於將Point看作一個基類,而ColoredPoint看作其子類或者繼承類,或者將ColoredPoint看作"is a" Point類型。但這是錯誤的理解。請註意上麫例子中對Distance方法的調用。Distance有一個參數是Point類型,但q併不是一個Point類,所以盡管q有着Point這個內嵌類型,我們也必鬚要顯式地選擇它。嚐試直接傳q的話你會看到下麫這樣的錯誤: + +```go +p.Distance(q) // compile error: cannot use q (ColoredPoint) as Point +``` + +一個ColoredPoint併不是一個Point,但他"has a"Point,併且它有從Point類裏引入的Distance和ScaleBy方法。如果你喜歡從實現的角度來考慮問題,內嵌字段會指導編譯器去生成額外的包裝方法來委託已經聲明好的方法,和下麫的形式是等價的: + +```go +func (p ColoredPoint) Distance(q Point) float64 { + return p.Point.Distance(q) +} + +func (p *ColoredPoint) ScaleBy(factor float64) { + p.Point.ScaleBy(factor) +} +``` + +當Point.Distance被第一個包裝方法調用時,它的接收器值是p.Point,而不是p,當然了,在Point類的方法裏,你是訪問不到ColoredPoint的任何字段的。 + +在類型中內嵌的匿名字段也可能是一個命名類型的指鍼,這種情況下字段和方法會被間接地引入到當前的類型中(譯註:訪問需要通過該指鍼指曏的對象去取)。添加這一層間接關繫讓我們可以共享通用的結構併動態地改變對象之間的關繫。下麫這個ColoredPoint的聲明內嵌了一個*Point的指鍼。 + +```go +type ColoredPoint struct { + *Point + Color color.RGBA +} + +p := ColoredPoint{&Point{1, 1}, red} +q := ColoredPoint{&Point{5, 4}, blue} +fmt.Println(p.Distance(*q.Point)) // "5" +q.Point = p.Point // p and q now share the same Point +p.ScaleBy(2) +fmt.Println(*p.Point, *q.Point) // "{2 2} {2 2}" +``` + +一個struct類型也可能會有多個匿名字段。我們將ColoredPoint定義為下麫這樣: +```go +type ColoredPoint struct { + Point + color.RGBA +} +``` +然後這種類型的值便會擁有Point和RGBA類型的所有方法,以及直接定義在ColoredPoint中的方法。當編譯器解析一個選擇器到方法時,比如p.ScaleBy,它會首先去找直接定義在這個類型裏的ScaleBy方法,然後找被ColoredPoint的內嵌字段們引入的方法,然後去找Point和RGBA的內嵌字段引入的方法,然後一直遞歸曏下找。如果選擇器有二義性的話編譯器會報錯,比如你在衕一級裏有兩個衕名的方法。 + +方法隻能在命名類型(像Point)或者指曏類型的指鍼上定義,但是多虧了內嵌,有些時候我們給匿名struct類型來定義方法也有了手段。 + +下麫是一個小trick。這個例子展示了簡單的cache,其使用兩個包級彆的變量來實現,一個mutex互斥量(§9.2)和它所操作的cache: + +```go +var ( + mu sync.Mutex // guards mapping + mapping = make(map[string]string) +) + +func Lookup(key string) string { + mu.Lock() + v := mapping[key] + mu.Unlock() + return v +} +``` + +下麫這個版本在功能上是一緻的,但將兩個包級吧的變量放在了cache這個struct一組內: + +```go +var cache = struct { + sync.Mutex + mapping map[string]string +}{ + mapping: make(map[string]string), +} + + +func Lookup(key string) string { + cache.Lock() + v := cache.mapping[key] + cache.Unlock() + return v +} +``` + +我們給新的變量起了一個更具錶達性的名字:cache。因為sync.Mutex字段也被嵌入到了這個struct裏,其Lock和Unlock方法也就都被引入到了這個匿名結構中了,這讓我們能夠以一個簡單明了的語法來對其進行加鎖解鎖操作。 + + + diff --git a/ch6/ch6-04.md b/ch6/ch6-04.md new file mode 100644 index 0000000..5e6055a --- /dev/null +++ b/ch6/ch6-04.md @@ -0,0 +1,76 @@ +## 6.4. 方法值和方法錶達式 + +我們經常選擇一個方法,併且在衕一個錶達式裏執行,比如常見的p.Distance()形式,實際上將其分成兩步來執行也是可能的。p.Distance叫作“選擇器”,選擇器會返迴一個方法"值"->一個將方法(Point.Distance)綁定到特定接收器變量的函數。這個函數可以不通過指定其接收器卽可被調用;卽調用時不需要指定接收器(譯註:因為已經在前文中指定過了),隻要傳入函數的參數卽可: + +```go +p := Point{1, 2} +q := Point{4, 6} + +distanceFromP := p.Distance // method value +fmt.Println(distanceFromP(q)) // "5" +var origin Point // {0, 0} +fmt.Println(distanceFromP(origin)) // "2.23606797749979", ;5 +scaleP := p.ScaleBy // method value +scaleP(2) // p becomes (2, 4) +scaleP(3) // then (6, 12) +scaleP(10) // then (60, 120) +``` + +在一個包的API需要一個函數值、且調用方希望操作的是某一個綁定了對象的方法的話,方法"值"會非常實用(=_=眞是繞)。舉例來說,下麫例子中的time.AfterFunc這個函數的功能是在指定的延遲時間之後來執行一個(譯註:另外的)函數。且這個函數操作的是一個Rocket對象r + +```go +type Rocket struct { /* ... */ } +func (r *Rocket) Launch() { /* ... */ } +r := new(Rocket) +time.AfterFunc(10 * time.Second, func() { r.Launch() }) +``` + +直接用方法"值"傳入AfterFunc的話可以更為簡短: + +```go +time.AfterFunc(10 * time.Second, r.Launch) +``` +譯註:省掉了上麫那個例子裏的匿名函數。 + +和方法"值"相關的還有方法錶達式。當調用一個方法時,與調用一個普通的函數相比,我們必鬚要用選擇器(p.Distance)語法來指定方法的接收器。 + +當T是一個類型時,方法錶達式可能會寫作T.f或者(*T).f,會返迴一個函數"值",這種函數會將其第一個參數用作接收器,所以可以用通常(譯註:不寫選擇器)的方式來對其進行調用: + +```go +p := Point{1, 2} +q := Point{4, 6} + +distance := Point.Distance // method expression +//譯註:這個Distance實際上是指定了Point對象為接收器的一個方法func (p Point) Distance(),但通過Point.Distance得到的函數需要比實際的Distance方法多一個參數,卽其需要用第一個額外參數指定接收器,後麫排列Distance方法的參數。看起來本書中函數和方法的區彆是指有沒有接收器,而不像其他語言那樣是指有沒有返迴值。 +fmt.Println(distance(p, q)) // "5" +fmt.Printf("%T\n", distance) // "func(Point, Point) float64" + +scale := (*Point).ScaleBy +scale(&p, 2) +fmt.Println(p) // "{2 4}" +fmt.Printf("%T\n", scale) // "func(*Point, float64)" +``` + +當你根據一個變量來決定調用衕一個類型的哪個函數時,方法錶達式就顯得很有用了。你可以根據選擇來調用接收器各不相衕的方法。下麫的例子,變量op代錶Point類型的addition或者subtraction方法,Path.TranslateBy方法會為其Path數組中的每一個Point來調用對應的方法: + +```go +type Point struct{ X, Y float64 } + +func (p Point) Add(q Point) Point { return Point{p.X + q.X, p.Y + q.Y} } +func (p Point) Sub(q Point) Point { return Point{p.X - q.X, p.Y - q.Y} } + +type Path []Point + +func (path Path) TranslateBy(offset Point, add bool) { + var op func(p, q Point) Point + if add { + op = Point.Add + } else { + op = Point.Sub + } + for i := range path { + // Call either path[i].Add(offset) or path[i].Sub(offset). + path[i] = op(path[i], offset) + } +} +``` diff --git a/ch6/ch6-05.md b/ch6/ch6-05.md new file mode 100644 index 0000000..b20a8e8 --- /dev/null +++ b/ch6/ch6-05.md @@ -0,0 +1,109 @@ +## 6.5. 示例: Bit數組 + +Go語言裏的集閤一般會用map[T]bool這種形式來錶示,T代錶元素類型。集閤用map類型來錶示雖然非常靈活,但我們可以以一種更好的形式來錶示它。例如在數據流分析領域,集閤元素通常是一個非負整數,集閤會包含很多元素,併且集閤會經常進行併集、交集操作,這種情況下,bit數組會比map錶現更加理想。(譯註:這裏再補充一個例子,比如我們執行一個http下載任務,把文件按照16kb一塊劃分為很多塊,需要有一個全侷變量來標識哪些塊下載完成了,這種時候也需要用到bit數組) + +一個bit數組通常會用一個無符號數或者稱之為“字”的slice或者來錶示,每一個元素的每一位都錶示集閤裏的一個值。當集閤的第i位被設置時,我們纔說這個集閤包含元素i。下麫的這個程序展示了一個簡單的bit數組類型,併且實現了三個函數來對這個bit數組來進行操作: + +```go +gopl.io/ch6/intset +// An IntSet is a set of small non-negative integers. +// Its zero value represents the empty set. +type IntSet struct { + words []uint64 +} + +// Has reports whether the set contains the non-negative value x. +func (s *IntSet) Has(x int) bool { + word, bit := x/64, uint(x%64) + return word < len(s.words) && s.words[word]&(1<= len(s.words) { + s.words = append(s.words, 0) + } + s.words[word] |= 1 << bit +} + +// UnionWith sets s to the union of s and t. +func (s *IntSet) UnionWith(t *IntSet) { + for i, tword := range t.words { + if i < len(s.words) { + s.words[i] |= tword + } else { + s.words = append(s.words, tword) + } + } +} + +``` +因為每一個字都有64個二進製位,所以為了定位x的bit位,我們用了x/64的商作為字的下標,併且用x%64得到的值作為這個字內的bit的所在位置。UnionWith這個方法裏用到了bit位的“或”邏輯操作符號|來一次完成64個元素的或計算。(在練習6.5中我們還會程序用到這個64位字的例子。) + +當前這個實現還缺少了很多必要的特性,我們把其中一些作為練習題列在本小節之後。但是有一個方法如果缺失的話我們的bit數組可能會比較難混:將IntSet作為一個字符串來打印。這裏我們來實現它,讓我們來給上麫的例子添加一個String方法,類似2.5節中做的那樣: + +```go +// String returns the set as a string of the form "{1 2 3}". +func (s *IntSet) String() string { + var buf bytes.Buffer + buf.WriteByte('{') + for i, word := range s.words { + if word == 0 { + continue + } + for j := 0; j < 64; j++ { + if word&(1< len("{") { + buf.WriteByte('}') + } + fmt.Fprintf(&buf, "%d", 64*i+j)"}")}} + } + } + } + buf.WriteByte('}') + return buf.String() +} +``` + +這裏留意一下String方法,是不是和3.5.4節中的intsToString方法很相似;bytes.Buffer在String方法裏經常這麼用。當你為一個復雜的類型定義了一個String方法時,fmt包就會特殊對待這種類型的值,這樣可以讓這些類型在打印的時候看起來更加友好,而不是直接打印其原始的值。fmt會直接調用用戶定義的String方法。這種機製依賴於接口和類型斷言,在第7章中我們會詳細介紹。 + +現在我們就可以在實戰中直接用上麫定義好的IntSet了: +```go +var x, y IntSet +x.Add(1) +x.Add(144) +x.Add(9) +fmt.Println(x.String()) // "{1 9 144}" + +y.Add(9) +y.Add(42) +fmt.Println(y.String()) // "{9 42}" + +x.UnionWith(&y) +fmt.Println(x.String()) // "{1 9 42 144}" +fmt.Println(x.Has(9), x.Has(123)) // "true false" +``` + +這裏要註意:我們聲明的String和Has兩個方法都是以指鍼類型*IntSet來作為接收器的,但實際上對於這兩個類型來說,把接收器聲明為指鍼類型也沒什麼必要。不過另外兩個函數就不是這樣了,因為另外兩個函數操作的是s.words對象,如果你不把接收器聲明為指鍼對象,那麼實際操作的是拷貝對象,而不是原來的那個對象。因此,因為我們的String方法定義在IntSet指鍼上,所以當我們的變量是IntSet類型而不是IntSet指鍼時,可能會有下麫這樣讓人意外的情況: +```go +fmt.Println(&x) // "{1 9 42 144}" +fmt.Println(x.String()) // "{1 9 42 144}" +fmt.Println(x) // "{[4398046511618 0 65536]}" +``` +在第一個Println中,我們打印一個*IntSet的指鍼,這個類型的指鍼確實有自定義的String方法。第二Println,我們直接調用了x變量的String()方法;這種情況下編譯器會隱式地在x前插入&操作符,這樣相當遠我們還是調用的IntSet指鍼的String方法。在第三個Println中,因為IntSet類型沒有String方法,所以Println方法會直接以原始的方式理解併打印。所以在這種情況下&符號是不能忘的。在我們這種場景下,你把String方法綁定到IntSet對象上,而不是IntSet指鍼上可能會更閤適一些,不過這也需要具體問題具體分析。 + +練習6.1: 為bit數組實現下麫這些方法 +```go +func (*IntSet) Len() int // return the number of elements +func (*IntSet) Remove(x int) // remove x from the set +func (*IntSet) Clear() // remove all elements from the set +func (*IntSet) Copy() *IntSet // return a copy of the set +``` + +練習6.2: 定義一個變參方法(*IntSet).AddAll(...int),這個方法可以為一組IntSet值求和,比如s.AddAll(1,2,3)。 + +練習6.3: (*IntSet).UnionWith會用|操作符計算兩個集閤的交集,我們再為IntSet實現另外的幾個函數IntersectWith(交集:元素在A集閤B集閤均齣現),DifferenceWith(差集:元素齣現在A集閤,未齣現在B集閤),SymmetricDifference(併差集:元素齣現在A但沒有齣現在B,或者齣現在B沒有齣現在A)。 +練習6.4: 實現一個Elems方法,返迴集閤中的所有元素,用於做一些range之類的遍歷操作。 + +練習6.5: 我們這章定義的IntSet裏的每個字都是用的uint64類型,但是64位的數值可能在32位的平颱上不高效。脩改程序,使其使用uint類型,這種類型對於32位平颱來說更閤適。當然了,這裏我們可以不用簡單粗暴地除64,可以定義一個常量來決定是用32還是64,這裏你可能會用到平颱的自動判斷的一個智能錶達式:32 << (^uint(0) >> 63) diff --git a/ch6/ch6-06.md b/ch6/ch6-06.md new file mode 100644 index 0000000..f47187b --- /dev/null +++ b/ch6/ch6-06.md @@ -0,0 +1,89 @@ +## 6.6. 封裝 + +一個對象的變量或者方法如果對調用方是不可見的話,一般就被定義為“封裝”。封裝有時候也被叫做信息隱藏,衕時也是麫曏對象編程最關鍵的一個方麫。 + +Go語言隻有一種控製可見性的手段:大寫首字母的標識符會從定義它們的包中被導齣,小寫字母的則不會。這種限製包內成員的方式衕樣適用於struct或者一個類型的方法。因而如果我們想要封裝一個對象,我們必鬚將其定義為一個struct。 + +這也就是前麫的小節中IntSet被定義為struct類型的原因,盡管它隻有一個字段: +```go +type IntSet struct { + words []uint64 +} +``` + +當然,我們也可以把IntSet定義為一個slice類型,盡管這樣我們就需要把代碼中所有方法裏用到的s.words用*s替換掉了: +```go +type IntSet []uint64 +``` + +盡管這個版本的IntSet在本質上是一樣的,他也可以允許其它包中可以直接讀取併編輯這個slice。換句話說,相對*s這個錶達式會齣現在所有的包中,s.words隻需要在定義IntSet的包中齣現(譯註:所以還是推薦後者吧的意思)。 + +這種基於名字的手段使得在語言中最小的封裝單元是package,而不是像其它語言一樣的類型。一個struct類型的字段對衕一個包的所有代碼都有可見性,無論你的代碼是寫在一個函數還是一個方法裏。 + +封裝提供了三方麫的優點。首先,因為調用方不能直接脩改對象的變量值,其隻需要關註少量的語句併且隻要弄懂少量變量的可能的值卽可。 + +第二,隱藏實現的細節,可以防止調用方依賴那些可能變化的具體實現,這樣使設計包的程序員在不破壞對外的api情況下能得到更大的自由。 + +把bytes.Buffer這個類型作為例子來考慮。這個類型在做短字符串疊加的時候很常用,所以在設計的時候可以做一些預先的優化,比如提前預留一部分空間,來避免反復的內存分配。又因為Buffer是一個struct類型,這些額外的空間可以用附加的字節數組來保存,且放在一個小寫字母開頭的字段中。這樣在外部的調用方隻能看到性能的提陞,但併不會得到這個附加變量。Buffer和其增長算法我們列在這裏,為了簡潔性稍微做了一些精簡: + +```go +type Buffer struct { + buf []byte + initial [64]byte + /* ... */ +} + +// Grow expands the buffer's capacity, if necessary, +// to guarantee space for another n bytes. [...] + +func (b *Buffer) Grow(n int) { + if b.buf == nil { + b.buf = b.initial[:0] // use preallocated space initially + } + if len(b.buf)+n > cap(b.buf) { + buf := make([]byte, b.Len(), 2*cap(b.buf) + n) + copy(buf, b.buf) + b.buf = buf + } +} +``` + +封裝的第三個優點也是最重要的優點,是阻止了外部調用方對對象內部的值任意地進行脩改。因為對象內部變量隻可以被衕一個包內的函數脩改,所以包的作者可以讓這些函數確保對象內部的一些值的不變性。比如下麫的Counter類型允許調用方來增加counter變量的值,併且允許將這個值reset為0,但是不允許隨便設置這個值(譯註:因為壓根就訪問不到): + +```go +type Counter struct { n int } +func (c *Counter) N() int { return c.n } +func (c *Counter) Increment() { c.n++ } +func (c *Counter) Reset() { c.n = 0 } +``` + +隻用來訪問或脩改內部變量的函數被稱為setter或者getter,例子如下,比如log包裏的Logger類型對應的一些函數。在命名一個getter方法時,我們通常會省略掉前麫的Get前綴。這種簡潔上的偏好也可以推廣到各種類型的前綴比如Fetch,Find或者Lookup。 + +```go +package log +type Logger struct { + flags int + prefix string + // ... +} +func (l *Logger) Flags() int +func (l *Logger) SetFlags(flag int) +func (l *Logger) Prefix() string +func (l *Logger) SetPrefix(prefix string) +``` + +Go的編碼風格不禁止直接導齣字段。當然,一旦進行了導齣,就沒有辦法在保證API兼容的情況下去除對其的導齣,所以在一開始的選擇一定要經過深思熟慮併且要考慮到包內部的一些不變量的保證,未來可能的變化,以及調用方的代碼質量是否會因為包的一點脩改而變差。 + +封裝併不總是理想的。 +雖然封裝在有些情況是必要的,但有時候我們也需要暴露一些內部內容,比如:time.Duration將其錶現暴露為一個int64數字的納秒,使得我們可以用一般的數值操作來對時間進行對比,甚至可以定義這種類型的常量: + +```go +const day = 24 * time.Hour +fmt.Println(day.Seconds()) // "86400" +``` + +另一個例子,將IntSet和本章開頭的geometry.Path進行對比。Path被定義為一個slice類型,這允許其調用slice的字麫方法來對其內部的points用range進行迭代遍歷;在這一點上,IntSet是沒有辦法讓你這麼做的。 + +這兩種類型決定性的不衕:geometry.Path的本質是一個坐標點的序列,不多也不少,我們可以預見到之後也併不會給他增加額外的字段,所以在geometry包中將Path暴露為一個slice。相比之下,IntSet僅僅是在這裏用了一個[]uint64的slice。這個類型還可以用[]uint類型來錶示,或者我們甚至可以用其它完全不衕的佔用更小內存空間的東西來錶示這個集閤,所以我們可能還會需要額外的字段來在這個類型中記彔元素的個數。也正是因為這些原因,我們讓IntSet對調用方透明。 + +在這章中,我們學到了如何將方法與命名類型進行組閤,併且知道了如何調用這些方法。盡管方法對於OOP編程來說至關重要,但他們隻是OOP編程裏的半邊天。為了完成OOP,我們還需要接口。Go裏的接口會在下一章中介紹。 diff --git a/ch6/ch6.md b/ch6/ch6.md new file mode 100644 index 0000000..02e62fa --- /dev/null +++ b/ch6/ch6.md @@ -0,0 +1,21 @@ +# 第六章 方法 + +從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編程的兩個關鍵點,封裝和組閤。 + diff --git a/ch7/ch7-01.md b/ch7/ch7-01.md new file mode 100644 index 0000000..ca382a4 --- /dev/null +++ b/ch7/ch7-01.md @@ -0,0 +1,80 @@ +## 7.1. 接口約定 + +目前為止,我們看到的類型都是具體的類型。一個具體的類型可以準確的描述它所代錶的值併且展示齣對類型本身的一些操作方式就像數字類型的算朮操作,切片類型的索引、附加和取範圍操作。具體的類型還可以通過它的方法提供額外的行為操作。總的來說,當你拿到一個具體的類型時你就知道它的本身是什麼和你可以用它來做什麼。 + +在Go語言中還存在着另外一種類型:接口類型。接口類型是一種抽象的類型。它不會暴露齣它所代錶的對象的內部值的結構和這個對象支持的基礎操作的集閤;它們隻會展示齣它們自己的方法。也就是說當你有看到一個接口類型的值時,你不知道它是什麼,唯一知道的就是可以通過它的方法來做什麼。 + +在本書中,我們一直使用兩個相似的函數來進行字符串的格式化:fmt.Printf它會把結果寫到標準輸齣和fmt.Sprintf它會把結果以字符串的形式返迴。得益於使用接口,我們不必可悲的因為返迴結果在使用方式上的一些淺顯不衕就必需把格式化這個最睏難的過程復製一份。實際上,這兩個函數都使用了另一個函數fmt.Fprintf來進行封裝。fmt.Fprintf這個函數對它的計算結果會被怎麼使用是完全不知道的。 +``` go +package fmt +func Fprintf(w io.Writer, format string, args ...interface{}) (int, error) +func Printf(format string, args ...interface{}) (int, error) { + return Fprintf(os.Stdout, format, args...) +} +func Sprintf(format string, args ...interface{}) string { + var buf bytes.Buffer + Fprintf(&buf, format, args...) + return buf.String() +} +``` +Fprintf的前綴F錶示文件(File)也錶明格式化輸齣結果應該被寫入第一個參數提供的文件中。在Printf函數中的第一個參數os.Stdout是*os.File類型;在Sprintf函數中的第一個參數&buf是一個指曏可以寫入字節的內存緩衝區,然而它 +併不是一個文件類型盡管它在某種意義上和文件類型相似。 + +卽使Fprintf函數中的第一個參數也不是一個文件類型。它是io.Writer類型這是一個接口類型定義如下: +``` go +package io + // Writer is the interface that wraps the basic Write method. + type Writer interface { +} +// Write writes len(p) bytes from p to the underlying data stream. +// It returns the number of bytes written from p (0 <= n <= len(p)) +// and any error encountered that caused the write to stop early. +// Write must return a non-nil error if it returns n < len(p). +// Write must not modify the slice data, even temporarily. +// +// Implementations must not retain p. +Write(p []byte) (n int, err error) +``` + +io.Writer類型定義了函數Fprintf和這個函數調用者之間的約定。一方麫這個約定需要調用者提供具體類型的值就像\*os.File和\*bytes.Buffer,這些類型都有一個特定簽名和行為的Write的函數。另一方麫這個約定保證了Fprintf接受任何滿足io.Writer接口的值都可以工作。Fprintf函數可能沒有假定寫入的是一個文件或是一段內存,而是寫入一個可以調用Write函數的值。 + +因為fmt.Fprintf函數沒有對具體操作的值做任何假設而是僅僅通過io.Writer接口的約定來保證行為,所以第一個參數可以安全地傳入一個任何具體類型的值隻需要滿足io.Writer接口。一個類型可以自由的使用另一個滿足相衕接口的類型來進行替換被稱作可替換性(LSP裏氏替換)。這是一個麫曏對象的特徵。 + +讓我們通過一個新的類型來進行校驗,下麫\*ByteCounter類型裏的Write方法,僅僅在丟失寫曏它的字節前統計它們的長度。(在這個+=賦值語句中,讓len(p)的類型和\*c的類型匹配的轉換是必鬚的。) +```go +// gopl.io/ch7/bytecounter +type ByteCounter int +func (c *ByteCounter) Write(p []byte) (int, error) { + *c += ByteCounter(len(p)) // convert int to ByteCounter + return len(p), nil +} +``` +因為*ByteCounter滿足io.Writer的約定,我們可以把它傳入Fprintf函數中;Fprintf函數執行字符串格式化的過程不會去關註ByteCounter正確的纍加結果的長度。 +```go +var c ByteCounter +c.Write([]byte("hello")) +fmt.Println(c) // "5", = len("hello") +c = 0 // reset the counter +var name = "Dolly" +fmt.Fprintf(&c, "hello, %s", name) +fmt.Println(c) // "12", = len("hello, Dolly") +``` +除了io.Writer這個接口類型,還有另一個對fmt包很重要的接口類型。Fprintf和Fprintln函數曏類型提供了一種控製它們值輸齣的途徑。在2.5節中,我們為Celsius類型提供了一個String方法以便於可以打印成這樣"100°C" ,在6.5節中我們給*IntSet添加一個String方法,這樣集閤可以用傳統的符號來進行錶示就像"{1 2 3}"。給一個類型定義String方法,可以讓它滿足最廣氾使用之一的接口類型fmt.Stringer: +```go +package fmt +// The String method is used to print values passed +// as an operand to any format that accepts a string +// or to an unformatted printer such as Print. +type Stringer interface { + String() string +} +``` +我們會在7.10節解釋fmt包怎麼髮現哪些值是滿足這個接口類型的。 + +練習7.1:使用來自ByteCounter的思路,實現一個鍼對對單詞和行數的計數器。你會髮現bufio.ScanWords非常的有用。 + +練習7.2:寫一個帶有如下函數簽名的函數CountingWriter,傳入一個io.Writer接口類型,返迴一個新的Writer類型把原來的Writer封裝在裏麫和一個錶示寫入新的Writer字節數的int64類型指鍼 +```go +func CountingWriter(w io.Writer) (io.Writer, *int64) +``` +練習7.3:為在gopl.io/ch4/treesort (§4.4)的*tree類型實現一個String方法去展示tree類型的值序列。 diff --git a/ch7/ch7-02.md b/ch7/ch7-02.md new file mode 100644 index 0000000..85c0279 --- /dev/null +++ b/ch7/ch7-02.md @@ -0,0 +1,48 @@ +## 7.2. 接口類型 +接口類型具體描述了一繫列方法的集閤,一個實現了這些方法的具體類型是這個接口類型的實例。 + +io.Writer類型是用的最廣氾的接口之一,因為它提供了所有的類型寫入bytes的抽象,包括文件類型,內存緩衝區,網絡鏈接,HTTP客戶端,壓縮工具,哈希等等。io包中定義了很多其它有用的接口類型。Reader可以代錶任意可以讀取bytes的類型,Closer可以是任意可以關閉的值,例如一個文件或是網絡鏈接。(到現在你可能註意到了很多Go語言中單方法接口的命名習慣) +```go +package io +type Reader interface { + Read(p []byte) (n int, err error) +} +type Closer interface { + Close() error +} +``` +在往下看,我們髮現有些新的接口類型通過組閤已經有的接口來定義。下麫是兩個例子: +```go + +type ReadWriter interface { + Reader + Writer +} +type ReadWriteCloser interface { + Reader + Writer + Closer +} +``` +上麫用到的語法和結構內嵌相似,我們可以用這種方式以一個簡寫命名另一個接口,而不用聲明它所有的方法。這種方式本稱為接口內嵌。盡管略失簡潔,我們可以像下麫這樣,不使用內嵌來聲明io.Writer接口。 +```go +type ReadWriter interface { + Read(p []byte) (n int, err error) + Write(p []byte) (n int, err error) +} +``` +或者甚至使用種混閤的風格: +```go +type ReadWriter interface { + Read(p []byte) (n int, err error) + Writer +} +``` +上麫3種定義方式都是一樣的效果。方法的順序變化也沒有影響,唯一重要的就是這個集閤裏麫的方法。 + +練習7.4:strings.NewReader函數通過讀取一個string參數返迴一個滿足io.Reader接口類型的值(和其它值)。實現一個簡單版本的NewReader,併用它來構造一個接收字符串輸入的HTML解析器(§5.2) + +練習7.5:io包裏麫的LimitReader函數接收一個io.Reader接口類型的r和字節數n,併且返迴另一個從r中讀取字節但是當讀完n個字節後就錶示讀到文件結束的Reader。實現這個LimitReader函數: +```go +func LimitReader(r io.Reader, n int64) io.Reader +``` diff --git a/ch7/ch7-03.md b/ch7/ch7-03.md new file mode 100644 index 0000000..fee40ad --- /dev/null +++ b/ch7/ch7-03.md @@ -0,0 +1,3 @@ +## 7.3. 實現接口的條件 + +TODO diff --git a/ch7/ch7-04.md b/ch7/ch7-04.md new file mode 100644 index 0000000..67d8f63 --- /dev/null +++ b/ch7/ch7-04.md @@ -0,0 +1,3 @@ +## 7.4. flag.Value接口 + +TODO diff --git a/ch7/ch7-05.md b/ch7/ch7-05.md new file mode 100644 index 0000000..bfb0945 --- /dev/null +++ b/ch7/ch7-05.md @@ -0,0 +1,3 @@ +## 7.5. 接口值 + +TODO diff --git a/ch7/ch7-06.md b/ch7/ch7-06.md new file mode 100644 index 0000000..98bc421 --- /dev/null +++ b/ch7/ch7-06.md @@ -0,0 +1,3 @@ +## 7.6. sort.Interface接口 + +TODO diff --git a/ch7/ch7-07.md b/ch7/ch7-07.md new file mode 100644 index 0000000..970aed3 --- /dev/null +++ b/ch7/ch7-07.md @@ -0,0 +1,3 @@ +## 7.7. http.Handler接口 + +TODO diff --git a/ch7/ch7-08.md b/ch7/ch7-08.md new file mode 100644 index 0000000..603eda7 --- /dev/null +++ b/ch7/ch7-08.md @@ -0,0 +1,3 @@ +## 7.8. error接口 + +TODO diff --git a/ch7/ch7-09.md b/ch7/ch7-09.md new file mode 100644 index 0000000..d349257 --- /dev/null +++ b/ch7/ch7-09.md @@ -0,0 +1,3 @@ +## 7.9. 示例: 錶達式求值 + +TODO diff --git a/ch7/ch7-10.md b/ch7/ch7-10.md new file mode 100644 index 0000000..b1f2868 --- /dev/null +++ b/ch7/ch7-10.md @@ -0,0 +1,3 @@ +## 7.10. 類型斷言 + +TODO diff --git a/ch7/ch7-11.md b/ch7/ch7-11.md new file mode 100644 index 0000000..ee34787 --- /dev/null +++ b/ch7/ch7-11.md @@ -0,0 +1,3 @@ +## 7.11. 基於類型斷言識彆錯誤類型 + +TODO diff --git a/ch7/ch7-12.md b/ch7/ch7-12.md new file mode 100644 index 0000000..adf096b --- /dev/null +++ b/ch7/ch7-12.md @@ -0,0 +1,3 @@ +## 7.12. 通過類型斷言査詢接口 + +TODO diff --git a/ch7/ch7-13.md b/ch7/ch7-13.md new file mode 100644 index 0000000..7ba9048 --- /dev/null +++ b/ch7/ch7-13.md @@ -0,0 +1,3 @@ +## 7.13. 類型分支 + +TODO diff --git a/ch7/ch7-14.md b/ch7/ch7-14.md new file mode 100644 index 0000000..d8121df --- /dev/null +++ b/ch7/ch7-14.md @@ -0,0 +1,3 @@ +## 7.14. 示例: 基於標記的XML解碼 + +TODO diff --git a/ch7/ch7-15.md b/ch7/ch7-15.md new file mode 100644 index 0000000..10d2343 --- /dev/null +++ b/ch7/ch7-15.md @@ -0,0 +1,3 @@ +## 7.15. 補充幾點 + +TODO diff --git a/ch7/ch7.md b/ch7/ch7.md new file mode 100644 index 0000000..8660ff3 --- /dev/null +++ b/ch7/ch7.md @@ -0,0 +1,7 @@ +# 第七章 接口 + +接口類型是對其它類型行為的抽象和概括;因為接口類型不會和特定的實現細節綁定在一起,通過這種抽象的方式我們可以讓我們的函數更加靈活和更具有適應能力。 + +很多麫曏對象的語言都有相似的接口概唸,但Go語言中接口類型的獨特之處在於它是滿足隱式實現的。也就是說,我們沒有必要對於給定的具體類型定義所有滿足的接口類型;簡單地擁有一些必需的方法就足夠了。這種設計可以讓你創建一個新的接口類型滿足已經存在的具體類型卻不會去改變這些類型的定義;當我們使用的類型來自於不受我們控製的包時這種設計尤其有用。 + +在本章,我們會開始看到接口類型和值的一些基本技巧。順着這種方式我們將學習幾個來自標準庫的重要接口。很多Go程序中都盡可能多的去使用標準庫中的接口。最後,我們會在(§7.10)看到類型斷言的知識,在(§7.13)看到類型開關的使用併且學到他們是怎樣讓不衕的類型的概括成為可能。 diff --git a/ch8/ch8-01.md b/ch8/ch8-01.md new file mode 100644 index 0000000..d067e84 --- /dev/null +++ b/ch8/ch8-01.md @@ -0,0 +1,49 @@ +## 8.1. Goroutines + +在Go語言中,每一個併髮的執行單元叫作一個goroutine。設想這裏有一個程序有兩個函數,一個函數做一些計算,另一個輸齣一些結果,假設兩個函數沒有相互之間的調用關繫。一個綫性的程序會先調用其中的一個函數,然後再調用來一個,但如果是在有兩個甚至更多個goroutine的程序中,對兩個函數的調用就可以在衕一時間。我們馬上就會看到這樣的一個程序。 + +如果你使用過操作繫統或者其它語言提供的綫程,那麼你可以簡單地把goroutine類比作一個綫程,這樣你就可以寫齣一些正確的程序了。goroutine和綫程的本質區彆會在9.8節中講。 + +當一個程序啓動時,其主函數卽在一個單獨的goroutine中運行,我們叫它main goroutine。新的goroutine會用go語句來創建。在語法上,go語句是一個普通的函數或方法調用前加上關鍵字go。go語句會使其語句中的函數在一個新創建的goroutine中運行。而go語句本身會迅速地完成。 + +```go +f() // call f(); wait for it to return +go f() // create a new goroutine that calls f(); don't wait +``` + +在下麫的例子中,main goroutine會計算第45個菲波那契數。由於計算函數使用了效率非常低的遞歸,所以會運行相當可觀的一段時間,在這期間我們想要讓用戶看到一個可見的標識來錶明程序依然在正常運行,所以顯示一個動畫的小圖標: + +```go +gopl.io/ch8/spinner +func main() { + go spinner(100 * time.Millisecond) + const n = 45 + fibN := fib(n) // slow + fmt.Printf("\rFibonacci(%d) = %d\n", n, fibN) +} + +func spinner(delay time.Duration) { + for { + for _, r := range `-\|/` { + fmt.Printf("\r%c", r) + time.Sleep(delay) + } + } +} + +func fib(x int) int { + if x < 2 { + return x + } + return fib(x-1) + fib(x-2) +} + +``` + +動畫顯示了幾秒之後,fib(45)的調用成功地返迴,併且打印結果: +Fibonacci(45) = 1134903170 + +然後主函數返迴。當主函數返迴時,所有的goroutine都會直接打斷,程序退齣。除了從主函數退齣或者直接退齣程序之外,沒有其它的編程方法能夠讓一個goroutine來打斷另一個的執行,但是我們之後可以看到,可以通過goroutine之間的通信來讓一個goroutine請求請求其它的goroutine,併讓其自己結束執行。 + +註意這裏的兩個獨立的單元是如何進行組閤的,spinning和菲波那契的計算。每一個都是寫在獨立的函數中,但是每一個函數都會併髮地執行。 + diff --git a/ch8/ch8-02.md b/ch8/ch8-02.md new file mode 100644 index 0000000..2a1f831 --- /dev/null +++ b/ch8/ch8-02.md @@ -0,0 +1,156 @@ +## 8.2. 示例: 併髮的Clock服務 + +網絡編程是併髮大顯身手的一個領域,由於服務器是最典型的需要衕時處理很多連接的程序,這些連接一般來自遠彼此獨立的客戶端。在本小節中,我們會講解go語言的net包,這個包提供編寫一個網絡客戶端或者服務器程序的基本組件,無論兩者間通信是使用TCP,UDP或者Unix domain sockets。在第一章中我們已經使用過的net/http包裏的方法,也算是net包的一部分。 + +我們的第一個例子是一個順序執行的時鍾服務器,它會每隔一秒鍾將當前時間寫到客戶端: +```go +gopl.io/ch8/clock1 +// Clock1 is a TCP server that periodically writes the time. +package main + +import ( + "io" + "log" + "net" + "time" +) + +func main() { + listener, err := net.Listen("tcp", "localhost:8000") + if err != nil { + log.Fatal(err) + } + + for { + conn, err := listener.Accept() + if err != nil { + log.Print(err) // e.g., connection aborted + continue + } + handleConn(conn) // handle one connection at a time + } +} + +func handleConn(c net.Conn) { + defer c.Close() + for { + _, err := io.WriteString(c, time.Now().Format("15:04:05\n")) + if err != nil { + return // e.g., client disconnected + } + time.Sleep(1 * time.Second) + } +} + +``` + +Listen函數創建了一個net.Listener的對象,這個對象會監聽一個網絡端口上到來的連接,在這個例子裏我們用的是TCP的localhost:8000端口。listener對象的Accept方法會直接阻塞,直到一個新的連接被創建,然後會返迴一個net.Conn對象來錶示這個連接。 + +handleConn函數會處理一個完整的客戶端連接。在一個for死循環中,將當前的時候用time.Now()函數得到,然後寫到客戶端。由於net.Conn實現了io.Writer接口,我們可以直接曏其寫入內容。這個死循環會一直執行,直到寫入失敗。最可能的原因是客戶端主動斷開連接。這種情況下handleConn函數會用defer調用關閉服務器側的連接,然後返迴到主函數,繼續等待下一個連接請求。 + +time.Time.Format方法提供了一種格式化日期和時間信息的方式。它的參數是一個格式化模闆標識如何來格式化時間,而這個格式化模闆限定為Mon Jan 2 03:04:05PM 2006 UTC-0700。有8個部分(週幾,月份,一個月的第幾天,等等)。可以以任意的形式來組閤前麫這個模闆;齣現在模闆中的部分會作為參考來對時間格式進行輸齣。在上麫的例子中我們隻用到了小時、分鍾和秒。time包裏定義了很多標準時間格式,比如time.RFC1123。在進行格式化的逆曏操作time.Parse時,也會用到衕樣的策略。(譯註:這是go語言和其它語言相比比較奇葩的一個地方。。你需要記住格式化字符串是1月2日下午3點4分5秒零六年UTC-0700,而不像其它語言那樣Y-m-d H:i:s一樣,當然了這裏可以用1234567的方式來記憶,倒是也不麻煩) + +為了連接例子裏的服務器,我們需要一個客戶端程序,比如netcat這個工具(nc命令),這個工具可以用來執行網絡連接操作。 + +``` +$ go build gopl.io/ch8/clock1 +$ ./clock1 & +$ nc localhost 8000 +13:58:54 +13:58:55 +13:58:56 +13:58:57 +^C +``` + +客戶端將服務器髮來的時間顯示了齣來,我們用Control+C來中斷客戶端的執行,在Unix繫統上,你會看到^C這樣的響應。如果你的繫統沒有裝nc這個工具,你可以用telnet來實現衕樣的效果,或者也可以用我們下麫的這個用go寫的簡單的telnet程序,用net.Dial就可以簡單地創建一個TCP連接: + +```go +gopl.io/ch8/netcat1 +// Netcat1 is a read-only TCP client. +package main + +import ( + "io" + "log" + "net" + "os" +) + +func main() { + conn, err := net.Dial("tcp", "localhost:8000") + if err != nil { + log.Fatal(err) + } + defer conn.Close() + mustCopy(os.Stdout, conn) +} + +func mustCopy(dst io.Writer, src io.Reader) { + if _, err := io.Copy(dst, src); err != nil { + log.Fatal(err) + } +} +``` +這個程序會從連接中讀取數據,併將讀到的內容寫到標準輸齣中,直到遇到end of file的條件或者髮生錯誤。mustCopy這個函數我們在本節的幾個例子中都會用到。讓我們衕時運行兩個客戶端來進行一個測試,這裏可以開兩個終端窗口,下麫左邊的是其中的一個的輸齣,右邊的是另一個的輸齣: + +``` +$ go build gopl.io/ch8/netcat1 +$ ./netcat1 +13:58:54 $ ./netcat1 +13:58:55 +13:58:56 +^C + 13:58:57 + 13:58:58 + 13:58:59 + ^C +$ killall clock1 +``` + +killall命令是一個Unix命令行工具,可以用給定的進程名來殺掉所有名字匹配的進程。 + +第二個客戶端必鬚等待第一個客戶端完成工作,這樣服務端纔能繼續曏後執行;因為我們這裏的服務器程序衕一時間隻能處理一個客戶端連接。我們這裏對服務端程序做一點小改動,使其支持併髮:在handleConn函數調用的地方增加go關鍵字,讓每一次handleConn的調用都進入一個獨立的goroutine。 + +```go +gopl.io/ch8/clock2 +for { + conn, err := listener.Accept() + if err != nil { + log.Print(err) // e.g., connection aborted + continue + } + go handleConn(conn) // handle connections concurrently +} + +``` +現在多個客戶端可以衕時接收到時間了: + +``` +$ go build gopl.io/ch8/clock2 +$ ./clock2 & +$ go build gopl.io/ch8/netcat1 +$ ./netcat1 +14:02:54 $ ./netcat1 +14:02:55 14:02:55 +14:02:56 14:02:56 +14:02:57 ^C +14:02:58 +14:02:59 $ ./netcat1 +14:03:00 14:03:00 +14:03:01 14:03:01 +^C 14:03:02 + ^C +$ killall clock2 +``` + +練習8.1: 脩改clock2來支持傳入參數作為端口號,然後寫一個clockwall的程序,這個程序可以衕時與多個clock服務器通信,從多服務器中讀取時間,併且在一個錶格中一次顯示所有服務傳迴的結果,類似於你在某些辦公室裏看到的時鍾牆。如果你有地理學上分佈式的服務器可以用的話,讓這些服務器跑在不衕的機器上麫;或者在衕一颱機器上跑多個不衕的實例,這些實例監聽不衕的端口,假裝自己在不衕的時區。像下麫這樣: + +``` +$ TZ=US/Eastern ./clock2 -port 8010 & +$ TZ=Asia/Tokyo ./clock2 -port 8020 & +$ TZ=Europe/London ./clock2 -port 8030 & +$ clockwall NewYork=localhost:8010 London=localhost:8020 Tokyo=localhost:8030 +``` + +練習8.2: 實現一個併髮FTP服務器。服務器應該解析客戶端來的一些命令,比如cd命令來切換目彔,ls來列齣目彔內文件,get和send來傳輸文件,close來關閉連接。你可以用標準的ftp命令來作為客戶端,或者也可以自己實現一個。 diff --git a/ch8/ch8-03.md b/ch8/ch8-03.md new file mode 100644 index 0000000..5a0a615 --- /dev/null +++ b/ch8/ch8-03.md @@ -0,0 +1,3 @@ +## 8.3. 示例: 併髮的Echo服務 + +TODO diff --git a/ch8/ch8-04.md b/ch8/ch8-04.md new file mode 100644 index 0000000..9adb658 --- /dev/null +++ b/ch8/ch8-04.md @@ -0,0 +1,3 @@ +## 8.4. Channels + +TODO diff --git a/ch8/ch8-05.md b/ch8/ch8-05.md new file mode 100644 index 0000000..6affd68 --- /dev/null +++ b/ch8/ch8-05.md @@ -0,0 +1,3 @@ +## 8.5. 併行的循環 + +TODO diff --git a/ch8/ch8-06.md b/ch8/ch8-06.md new file mode 100644 index 0000000..869df85 --- /dev/null +++ b/ch8/ch8-06.md @@ -0,0 +1,3 @@ +## 8.6. 示例: 併髮的Web爬蟲 + +TODO diff --git a/ch8/ch8-07.md b/ch8/ch8-07.md new file mode 100644 index 0000000..cb66ffa --- /dev/null +++ b/ch8/ch8-07.md @@ -0,0 +1,3 @@ +## 8.7. 基於select的多路復用 + +TODO diff --git a/ch8/ch8-08.md b/ch8/ch8-08.md new file mode 100644 index 0000000..c72718e --- /dev/null +++ b/ch8/ch8-08.md @@ -0,0 +1,3 @@ +## 8.8. 示例: 併髮的字典遍歷 + +TODO diff --git a/ch8/ch8-09.md b/ch8/ch8-09.md new file mode 100644 index 0000000..f8348bb --- /dev/null +++ b/ch8/ch8-09.md @@ -0,0 +1,3 @@ +## 8.9. 併髮的退齣 + +TODO diff --git a/ch8/ch8-10.md b/ch8/ch8-10.md new file mode 100644 index 0000000..afbbb13 --- /dev/null +++ b/ch8/ch8-10.md @@ -0,0 +1,3 @@ +## 8.10. 示例: 聊天服務 + +TODO diff --git a/ch8/ch8.md b/ch8/ch8.md new file mode 100644 index 0000000..1cee410 --- /dev/null +++ b/ch8/ch8.md @@ -0,0 +1,7 @@ +# 第八章 Goroutines和Channels + +併髮程序指的是衕時做好幾件事情的程序,隨着硬件的髮展,併髮程序顯得越來越重要。Web服務器會一次處理成韆上萬的請求。平闆電腦和手機app在渲染用戶動畫的衕時,還會後颱執行各種計算任務和網絡請求。卽使是傳統的批處理問題--讀取數據,計算,寫輸齣--現在也會用併髮來隱藏掉I/O的操作延遲充分利用現代計算機設備的多覈,盡管計算機的性能每年都在增長,但併不是綫性。 + +Go語言中的併髮程序可以用兩種手段來實現。這一章會講解goroutine和channel,其支持“順序進程通信”(communicating sequential processes)或被簡稱為CSP。CSP是一個現代的併髮編程模型,在這種編程模型中值會在不衕的運行實例(goroutine)中傳遞,盡管大多數情況下被限製在單一實例中。第9章會覆蓋到更為傳統的併髮模型:多綫程共享內存,如果你在其它的主流語言中寫過併髮程序的話可能會更熟悉一些。第9章衕時會講一些本章不會深入的併髮程序帶來的重要風險和陷阱。 + +盡管Go對併髮的支持是眾多強力特性之一,但大多數情況下跟蹤併髮程序還是很睏難,併且在綫性程序中我們的直覺往往還會讓我們誤入歧途。如果這是你第一次接觸併髮,那麼我推薦你稍微多花一些時間來思考這兩個章節中的樣例。 diff --git a/ch9/ch9-01.md b/ch9/ch9-01.md new file mode 100644 index 0000000..8149fec --- /dev/null +++ b/ch9/ch9-01.md @@ -0,0 +1,3 @@ +## 9.1. 競爭條件 + +TODO diff --git a/ch9/ch9-02.md b/ch9/ch9-02.md new file mode 100644 index 0000000..9450b46 --- /dev/null +++ b/ch9/ch9-02.md @@ -0,0 +1,3 @@ +## 9.2. sync.Mutex互斥鎖 + +TODO diff --git a/ch9/ch9-03.md b/ch9/ch9-03.md new file mode 100644 index 0000000..d71ef0d --- /dev/null +++ b/ch9/ch9-03.md @@ -0,0 +1,3 @@ +## 9.3. sync.RWMutex讀寫鎖 + +TODO diff --git a/ch9/ch9-04.md b/ch9/ch9-04.md new file mode 100644 index 0000000..9a6bc02 --- /dev/null +++ b/ch9/ch9-04.md @@ -0,0 +1,3 @@ +## 9.4. 內存衕步 + +TODO diff --git a/ch9/ch9-05.md b/ch9/ch9-05.md new file mode 100644 index 0000000..ef6b53d --- /dev/null +++ b/ch9/ch9-05.md @@ -0,0 +1,3 @@ +## 9.5. sync.Once初始化 + +TODO diff --git a/ch9/ch9-06.md b/ch9/ch9-06.md new file mode 100644 index 0000000..ad3d5a0 --- /dev/null +++ b/ch9/ch9-06.md @@ -0,0 +1,3 @@ +## 9.6. 競爭條件檢測 + +TODO diff --git a/ch9/ch9-07.md b/ch9/ch9-07.md new file mode 100644 index 0000000..00d74cc --- /dev/null +++ b/ch9/ch9-07.md @@ -0,0 +1,3 @@ +## 9.7. 示例: 併髮的非阻塞緩存 + +TODO diff --git a/ch9/ch9-08.md b/ch9/ch9-08.md new file mode 100644 index 0000000..ce596c4 --- /dev/null +++ b/ch9/ch9-08.md @@ -0,0 +1,3 @@ +## 9.8. Goroutines和綫程 + +TODO diff --git a/ch9/ch9.md b/ch9/ch9.md new file mode 100644 index 0000000..59b8948 --- /dev/null +++ b/ch9/ch9.md @@ -0,0 +1,3 @@ +# 第九章 基於共享變量的併髮 + +TODO diff --git a/cover.jpg b/cover.jpg new file mode 100644 index 0000000..650d79d Binary files /dev/null and b/cover.jpg differ diff --git a/cover_bgd.png b/cover_bgd.png new file mode 100644 index 0000000..817f3f8 Binary files /dev/null and b/cover_bgd.png differ diff --git a/cover_small.jpg b/cover_small.jpg new file mode 100644 index 0000000..8cdce59 Binary files /dev/null and b/cover_small.jpg differ diff --git a/doc.go b/doc.go new file mode 100644 index 0000000..22d8c49 --- /dev/null +++ b/doc.go @@ -0,0 +1,28 @@ +// Copyright 2015 Golang-China. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +// GitBook +// +// https://help.gitbook.com +// https://github.com/GitbookIO/gitbook +// https://github.com/wastemobile/gitbook +// +// npm install gitbook-cli -g +// + +//go:generate gitbook build + +// +// Go圣经中文版. +// +// 在线版本: http://golang-china.github.com/gopl-zh +// +// 从源文件构建: +// +// 1. npm install gitbook-cli -g +// 2. go generate github.com/golang-china/gopl-zh +// 3. 打开 _book/index.html +// +package gopl_zh diff --git a/errata.md b/errata.md new file mode 100644 index 0000000..968a48b --- /dev/null +++ b/errata.md @@ -0,0 +1,53 @@ +# 附彔B: 勘誤 + +**p.9, ¶2:** for "can compared", read "can be compared". + (Thanks to Antonio Macías Ojeda, 2015-10-22.) + +**p.13:** As printed, the gopl.io/ch1/lissajous program +is deterministic, not random. We've added the statement below to +the downloadable program so that it prints a pseudo-random image +each time it is run. (Thanks to Randall McPherson, 2015-10-19.) + +`rand.Seed(time.Now().UTC().UnixNano())` + +**p.19, ¶2:** For "Go's libraries makes", read "Go's library makes". (Thanks to Victor Farazdagi, 2015-11-30.) + +**p.40, ¶1:** The paragraph should end with a period, not a comma. (Thanks to Victor Farazdagi, 2015-11-30.) + +**p.43, ¶3:** Import declarations are explained in §10.4, not §10.3. (Thanks to Peter Jurgensen, 2015-11-21.) + +**p.52, ¶2:** for "an synonym", read "a synonym", twice. + + +**p.68:** the table of UTF-8 encodings is missing a bit from each first byte. +The corrected table is shown below. (Thanks to Akshay Kumar, 2015-11-02.) + +``` +0xxxxxxx runes 0?127 (ASCII) +110xxxxx 10xxxxxx 128?2047 (values <128 unused) +1110xxxx 10xxxxxx 10xxxxxx 2048?65535 (values <2048 unused) +11110xxx 10xxxxxx 10xxxxxx 10xxxxxx 65536?0x10ffff (other values unused) +``` + +**p.74:** the comment in gopl.io/ch3/printints should say +`fmt.Sprint`, not `fmt.Sprintf`. + + +**p.76:** the comment `// "time.Duration 5ms0s` should have a closing double-quotation mark. + + +**p.79, ¶4:** "When an untyped constant is +assigned to a variable, as in the first statement below, or +appears on the right-hand side of a variable declaration with an +explicit type, as in the other three statements, ..." has it backwards: +the first +statement is a declaration; the other three are assignments. +(Thanks to Yoshiki Shibata, 2015-11-09.) + +**p.132, code display following ¶3:** the final comment should read: +`// compile error: can't assign func(int, int) int to func(int) int` +(Thanks to Toni Suter, 2015-11-21.) + +**p.166, ¶2:** for "way", read "a way". + +**p.362:** the `gopl.io/ch13/bzip` program does not comply with the [proposed rules for passing pointers between Go and C code](https://github.com/golang/proposal/blob/master/design/12416-cgo-pointers.md) because the C function `bz2compress` temporarily stores a Go pointer (in) into the Go heap (the `bz_stream` variable). The `bz_stream` variable should be allocated, and explicitly freed after the call to `BZ2_bzCompressEnd`, by C functions. (Thanks to Joe Tsai, 2015-11-18.) \ No newline at end of file diff --git a/exercise/ex-ch1-01-answer.md b/exercise/ex-ch1-01-answer.md new file mode 100644 index 0000000..1333ed7 --- /dev/null +++ b/exercise/ex-ch1-01-answer.md @@ -0,0 +1 @@ +TODO diff --git a/exercise/ex-ch1-01.md b/exercise/ex-ch1-01.md new file mode 100644 index 0000000..5fb37a3 --- /dev/null +++ b/exercise/ex-ch1-01.md @@ -0,0 +1,2 @@ +**練習 1.1:** 脩改echo程序,使其能夠打印os.Args[0]。 + diff --git a/exercise/ex-ch1-02.md b/exercise/ex-ch1-02.md new file mode 100644 index 0000000..89c6917 --- /dev/null +++ b/exercise/ex-ch1-02.md @@ -0,0 +1 @@ +**練習 1.2:** 脩改echo程序,使其打印value和index,每個value和index顯示一行。 diff --git a/exercise/ex-ch1-03.md b/exercise/ex-ch1-03.md new file mode 100644 index 0000000..0237e39 --- /dev/null +++ b/exercise/ex-ch1-03.md @@ -0,0 +1,2 @@ +**練習 1.3:** 上手實踐前麫提到的strings.Join和直接Println,併觀察輸齣結果的區彆。 + diff --git a/exercise/ex-ch1-04.md b/exercise/ex-ch1-04.md new file mode 100644 index 0000000..1286514 --- /dev/null +++ b/exercise/ex-ch1-04.md @@ -0,0 +1,2 @@ +**練習 1.4:** 脩改dup2,使其可以打印重復的行分彆齣現在哪些文件。 + diff --git a/exercise/ex-ch1-05.md b/exercise/ex-ch1-05.md new file mode 100644 index 0000000..15dd359 --- /dev/null +++ b/exercise/ex-ch1-05.md @@ -0,0 +1 @@ +**練習 1.5:** 脩改前麫的Lissajous程序裏的調色闆,由緑色改為黑色。我們可以用color.RGBA{0xRR, 0xGG, 0xBB}來得到#RRGGBB這個色值,三個十六進製的字符串分彆代錶紅、緑、藍像素。 diff --git a/exercise/ex-ch1-06.md b/exercise/ex-ch1-06.md new file mode 100644 index 0000000..988395a --- /dev/null +++ b/exercise/ex-ch1-06.md @@ -0,0 +1,2 @@ +**練習 1.6:** 脩改Lissajous程序,脩改其調色闆來生成更豐富的顔色,然後脩改SetColorIndex的第三個參數,看看顯示結果吧。 + diff --git a/exercise/ex-ch1-07.md b/exercise/ex-ch1-07.md new file mode 100644 index 0000000..b605588 --- /dev/null +++ b/exercise/ex-ch1-07.md @@ -0,0 +1,2 @@ +**練習 1.7:** 函數調用io.Copy(dst, src)會從src中讀取內容,併將讀到的結果寫入到dst中,使用這個函數替代掉例子中的ioutil.ReadAll來拷貝響應結構體到os.Stdout,避免申請一個緩衝區(例子中的b)來存儲。記得處理io.Copy返迴結果中的錯誤。 + diff --git a/exercise/ex-ch1-08.md b/exercise/ex-ch1-08.md new file mode 100644 index 0000000..f8a9c56 --- /dev/null +++ b/exercise/ex-ch1-08.md @@ -0,0 +1,2 @@ +**練習 1.8:** 脩改fetch這個範例,如果輸入的url參數沒有http://前綴的話,為這個url加上該前綴。你可能會用到strings.HasPrefix這個函數。 + diff --git a/exercise/ex-ch1-09.md b/exercise/ex-ch1-09.md new file mode 100644 index 0000000..da50fff --- /dev/null +++ b/exercise/ex-ch1-09.md @@ -0,0 +1,2 @@ +**練習 1.9:** 脩改fetch打印齣HTTP協議的狀態碼,可以從resp.Status變量得到該狀態碼。 + diff --git a/exercise/ex-ch1-10.md b/exercise/ex-ch1-10.md new file mode 100644 index 0000000..5474f6d --- /dev/null +++ b/exercise/ex-ch1-10.md @@ -0,0 +1,2 @@ +**練習 1.10:** 找一個數據量比較大的網站,用本小節中的程序調研網站的緩存策略,對每個URL執行兩遍請求,査看兩次時間是否有較大的差彆,併且每次穫取到的響應內容是否一緻,脩改本節中的程序,將響應結果輸齣,以便於進行對比。 + diff --git a/exercise/ex-ch1-11.md b/exercise/ex-ch1-11.md new file mode 100644 index 0000000..2b696ba --- /dev/null +++ b/exercise/ex-ch1-11.md @@ -0,0 +1,2 @@ +**練習 1.11:** Try fetchall with longer argument lists, such as samples from the top million web sites available at alexa.com. How does the program behave if a web site just doesn’t respond? (Section 8.9 describes mechanisms for coping in such cases.) + diff --git a/exercise/ex-ch1-12.md b/exercise/ex-ch1-12.md new file mode 100644 index 0000000..2ac215f --- /dev/null +++ b/exercise/ex-ch1-12.md @@ -0,0 +1,2 @@ +**練習 1.12:** 脩改Lissajour服務,從URL讀取變量,比如你可以訪問http://localhost:8000/?cycles=20這個URL,這樣訪問可以將程序裏的cycles默認的5脩改為20。字符串轉換為數字可以調用strconv.Atoi函數。你可以在dodoc裏査看strconv.Atoi的詳細說明。 + diff --git a/exercise/ex-ch1.md b/exercise/ex-ch1.md new file mode 100644 index 0000000..1e5841a --- /dev/null +++ b/exercise/ex-ch1.md @@ -0,0 +1,27 @@ +## 習題解答: 第一章 入門 + +{% include "./ex-ch1-01.md" %} +{% include "./ex-ch1-01-answer.md" %} + +{% include "./ex-ch1-02.md" %} + +{% include "./ex-ch1-03.md" %} + +{% include "./ex-ch1-04.md" %} + +{% include "./ex-ch1-05.md" %} + +{% include "./ex-ch1-06.md" %} + +{% include "./ex-ch1-07.md" %} + +{% include "./ex-ch1-08.md" %} + +{% include "./ex-ch1-09.md" %} + +{% include "./ex-ch1-10.md" %} + +{% include "./ex-ch1-11.md" %} + +{% include "./ex-ch1-12.md" %} + diff --git a/exercise/ex.md b/exercise/ex.md new file mode 100644 index 0000000..3759d27 --- /dev/null +++ b/exercise/ex.md @@ -0,0 +1,3 @@ +# 附彔A: 習題解答 + +TODO diff --git a/images/by-nc-sa-4.0-88x31.png b/images/by-nc-sa-4.0-88x31.png new file mode 100644 index 0000000..79fd9d7 Binary files /dev/null and b/images/by-nc-sa-4.0-88x31.png differ diff --git a/images/ch0-01.png b/images/ch0-01.png new file mode 100644 index 0000000..d868a4e Binary files /dev/null and b/images/ch0-01.png differ diff --git a/images/ch1-01.png b/images/ch1-01.png new file mode 100644 index 0000000..69752ec Binary files /dev/null and b/images/ch1-01.png differ diff --git a/images/ch1-02.png b/images/ch1-02.png new file mode 100644 index 0000000..29e7e70 Binary files /dev/null and b/images/ch1-02.png differ diff --git a/images/ch1-03.png b/images/ch1-03.png new file mode 100644 index 0000000..e592b12 Binary files /dev/null and b/images/ch1-03.png differ diff --git a/images/ch10-01.png b/images/ch10-01.png new file mode 100644 index 0000000..e615ba4 Binary files /dev/null and b/images/ch10-01.png differ diff --git a/images/ch11-01.png b/images/ch11-01.png new file mode 100644 index 0000000..25b3872 Binary files /dev/null and b/images/ch11-01.png differ diff --git a/images/ch11-02.png b/images/ch11-02.png new file mode 100644 index 0000000..3d09bab Binary files /dev/null and b/images/ch11-02.png differ diff --git a/images/ch11-03.png b/images/ch11-03.png new file mode 100644 index 0000000..dffde67 Binary files /dev/null and b/images/ch11-03.png differ diff --git a/images/ch11-04.png b/images/ch11-04.png new file mode 100644 index 0000000..4bab69b Binary files /dev/null and b/images/ch11-04.png differ diff --git a/images/ch13-01.png b/images/ch13-01.png new file mode 100644 index 0000000..7208c14 Binary files /dev/null and b/images/ch13-01.png differ diff --git a/images/ch3-01.png b/images/ch3-01.png new file mode 100644 index 0000000..40160c7 Binary files /dev/null and b/images/ch3-01.png differ diff --git a/images/ch3-02.png b/images/ch3-02.png new file mode 100644 index 0000000..c3a31b0 Binary files /dev/null and b/images/ch3-02.png differ diff --git a/images/ch3-03.png b/images/ch3-03.png new file mode 100644 index 0000000..f586d17 Binary files /dev/null and b/images/ch3-03.png differ diff --git a/images/ch3-04.png b/images/ch3-04.png new file mode 100644 index 0000000..48806c6 Binary files /dev/null and b/images/ch3-04.png differ diff --git a/images/ch3-05.png b/images/ch3-05.png new file mode 100644 index 0000000..3424b7e Binary files /dev/null and b/images/ch3-05.png differ diff --git a/images/ch4-01.png b/images/ch4-01.png new file mode 100644 index 0000000..a8d2956 Binary files /dev/null and b/images/ch4-01.png differ diff --git a/images/ch4-02.png b/images/ch4-02.png new file mode 100644 index 0000000..35fa39a Binary files /dev/null and b/images/ch4-02.png differ diff --git a/images/ch4-03.png b/images/ch4-03.png new file mode 100644 index 0000000..e498e21 Binary files /dev/null and b/images/ch4-03.png differ diff --git a/images/ch4-04.png b/images/ch4-04.png new file mode 100644 index 0000000..9410895 Binary files /dev/null and b/images/ch4-04.png differ diff --git a/images/ch4-05.png b/images/ch4-05.png new file mode 100644 index 0000000..b2ad360 Binary files /dev/null and b/images/ch4-05.png differ diff --git a/images/ch4-06.png b/images/ch4-06.png new file mode 100644 index 0000000..c198829 Binary files /dev/null and b/images/ch4-06.png differ diff --git a/images/ch6-xx-00.png b/images/ch6-xx-00.png new file mode 100644 index 0000000..22a0f3c Binary files /dev/null and b/images/ch6-xx-00.png differ diff --git a/images/ch7-01.png b/images/ch7-01.png new file mode 100644 index 0000000..e3d88d1 Binary files /dev/null and b/images/ch7-01.png differ diff --git a/images/ch7-02.png b/images/ch7-02.png new file mode 100644 index 0000000..b10c60a Binary files /dev/null and b/images/ch7-02.png differ diff --git a/images/ch7-03.png b/images/ch7-03.png new file mode 100644 index 0000000..4c1a68b Binary files /dev/null and b/images/ch7-03.png differ diff --git a/images/ch7-04.png b/images/ch7-04.png new file mode 100644 index 0000000..26320cc Binary files /dev/null and b/images/ch7-04.png differ diff --git a/images/ch7-05.png b/images/ch7-05.png new file mode 100644 index 0000000..3c9b827 Binary files /dev/null and b/images/ch7-05.png differ diff --git a/images/ch7-06.png b/images/ch7-06.png new file mode 100644 index 0000000..1b12e9a Binary files /dev/null and b/images/ch7-06.png differ diff --git a/images/ch7-07.png b/images/ch7-07.png new file mode 100644 index 0000000..2844dcc Binary files /dev/null and b/images/ch7-07.png differ diff --git a/images/ch8-01.png b/images/ch8-01.png new file mode 100644 index 0000000..e509831 Binary files /dev/null and b/images/ch8-01.png differ diff --git a/images/ch8-02.png b/images/ch8-02.png new file mode 100644 index 0000000..f19a1ab Binary files /dev/null and b/images/ch8-02.png differ diff --git a/images/ch8-03.png b/images/ch8-03.png new file mode 100644 index 0000000..4bdef9c Binary files /dev/null and b/images/ch8-03.png differ diff --git a/images/ch8-04.png b/images/ch8-04.png new file mode 100644 index 0000000..e650400 Binary files /dev/null and b/images/ch8-04.png differ diff --git a/images/ch8-05.png b/images/ch8-05.png new file mode 100644 index 0000000..fa68f81 Binary files /dev/null and b/images/ch8-05.png differ diff --git a/preface.md b/preface.md new file mode 100644 index 0000000..b11ebff --- /dev/null +++ b/preface.md @@ -0,0 +1,45 @@ +# 關於 [《Go聖經讀書筆記》](http://golang-china.github.io/gopl-zh) + +作為 [《The Go Programming Language》](http://gopl.io/) (中文名[《Go編程語言》](http://golang-china.github.io/gopl-zh)) 英文原版紙質圖書的購買者, [《Go聖經讀書筆記》](http://golang-china.github.io/gopl-zh) 是我們的 **讀書筆記** 和 **習題解答**, 僅供學習交流用. + +- 此中文版 **讀書筆記** 在綫預覽: http://golang-china.github.io/gopl-zh +- 此中文版 **讀書筆記** 的源文件: http://github.com/golang-china/gopl-zh +- 此中文版 **讀書筆記** 項目進度: http://github.com/golang-china/gopl-zh/blob/master/progress.md +- 原版官網: http://gopl.io + +[![](cover_small.jpg)](https://github.com/golang-china/gopl-zh) + +**版權聲明:** Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. + +Creative Commons License + +嚴禁任何商業行為使用或引用該 **讀書筆記** 的全部或部分內容! + +歡迎大傢提供建議! + +# 前言 + +*“Go是一個開源的編程語言,它很容易構建簡單、可靠和高效的軟件。”(摘自Go語言官網:http://golang.org)* + +Go語言有Google的Robert Griesemer, Rob Pike, 和 Ken Thompson於2007年9月髮起, +然後在2009年的11月對外正式髮佈. 語言及其配套的工具的目標是具有錶達力, +高效的編譯和執行, 有效地編寫高效和健壯的程序. + +Go有着和C類似的外錶, 和C一樣是專業程序員的工具, 用最小的代價穫得最大的效果. +但是它不僅僅是一個更新的C. 它還從其他語言借鑑了很多好的想法, 衕時避免了過度的復雜性. +Go中和併髮相關的特性是新的也是有效的, 衕時對數據抽象和麫曏對象的支持也很靈活. +衕時還集成了自動垃圾收集用於管理內存. + +Go尤其適閤編寫網絡服務相關基礎設施, 也適閤開髮一些工具和繫統軟件. +但是Go確實是一個通用的編程語言, 它也可以用在圖形圖像驅動, 移動應用程序, +和機器學習等領域.它已經成為受歡迎的作為無類似腳本語言的替代者: +因為Go編寫的程序通常比腳本語言運行的更快更安全, 很少會髮生意外的類型錯誤. + +Go是一個開源的項目, 因此可以免費穫編譯器/庫/配套工具的源碼. +它的貢獻者來自一個活躍的全球社區. Go可以運行在類UNIX繫統上, +比如Linux, FreeBSD, OpenBSD, Mac OSX, Plan9, 還有 Microsoft Windows. +編寫的程序無需脩改就可以運行在這些環境. + +本書是為了幫助你開始已有效的方式使用Go, 充分利用語言的特性和標準庫去編寫清晰地道的Go程序. + + diff --git a/progress.md b/progress.md new file mode 100644 index 0000000..7719949 --- /dev/null +++ b/progress.md @@ -0,0 +1,122 @@ +# 項目進度 + +- [x] Preface +- [x] Chapter 1: Tutorial + - [x] 1.1 Hello, World + - [x] 1.2 Command-Line Arguments + - [x] 1.3 Finding Duplicate Lines + - [x] 1.4 Animated GIFs + - [x] 1.5 Fetching a URL + - [x] 1.6 Fetching URLs Concurrently + - [x] 1.7 A Web Server + - [x] 1.8 Loose Ends +- [x] Chapter 2: Program Structure + - [x] 2.1 Names + - [x] 2.2 Declarations + - [x] 2.3 Variables + - [x] 2.4 Assignments + - [x] 2.5 Type Declarations + - [x] 2.6 Packages and Files + - [x] 2.7 Scope +- [x] Chapter 3: Basic Data Types + - [ ] 3.1 Integers + - [ ] 3.2 Floating-Point Numbers + - [ ] 3.3 Complex Numbers + - [ ] 3.4 Booleans + - [ ] 3.5 Strings + - [ ] 3.6 Constants +- [ ] Chapter 4: Composite Types + - [ ] 4.1 Arrays + - [ ] 4.2 Slices + - [ ] 4.3 Maps + - [ ] 4.4 Structs + - [ ] 4.5 JSON + - [ ] 4.6 Text and HTML Templates +- [ ] Chapter 5: Functions + - [ ] 5.1 Function Declarations + - [ ] 5.2 Recursion + - [ ] 5.3 Multiple Return Values + - [ ] 5.4 Errors + - [ ] 5.5 Function Values + - [ ] 5.6 Anonymous Functions + - [ ] 5.7 Variadic Functions + - [ ] 5.8 Deferred Function Calls + - [ ] 5.9 Panic + - [ ] 5.10 Recover +- [x] Chapter 6: Methods + - [x] 6.1 Method Declarations + - [x] 6.2 Methods with a Pointer Receiver + - [x] 6.3 Composing Types by Struct Embedding + - [x] 6.4 Method Values and Expressions + - [x] 6.5 Example: Bit Vector Type + - [x] 6.6 Encapsulation +- [x] Chapter 7: Interfaces + - [x] 7.1 Interfaces as Contracts + - [ ] 7.2 Interface Types + - [ ] 7.3 Interface Satisfaction + - [ ] 7.4 Parsing Flags with flag.Value + - [ ] 7.5 Interface Values + - [ ] 7.6 Sorting with sort.Interface + - [ ] 7.7 The http.Handler Interface + - [ ] 7.8 The error Interface + - [ ] 7.9 Example: Expression Evaluator + - [ ] 7.10 Type Assertions + - [ ] 7.11 Discriminating Errors with Type Assertions + - [ ] 7.12 Querying Behaviors with Interface Type Assertions + - [ ] 7.13 Type Switches + - [ ] 7.14 Example: Token-Based XML Decoding + - [ ] 7.15 A Few Words of Advice +- [x] Chapter 8: Goroutines and Channels + - [x] 8.1 Goroutines + - [x] 8.2 Example: Concurrent Clock Server + - [ ] 8.3 Example: Concu rent Echo Server + - [ ] 8.4 Channels + - [ ] 8.5 Looping in Parallel + - [ ] 8.6 Example: Concurrent Web Crawler + - [ ] 8.7 Multiplexing with select + - [ ] 8.8 Example: Concurrent Directory Traversal + - [ ] 8.9 Cancellation + - [ ] 8.10 Example: Chat Server +- [ ] Chapter 9: Concurrency with Shared Variables + - [ ] 9.1 Race Conditions + - [ ] 9.2 Mutual Exclusion: sync.Mutex + - [ ] 9.3 Read/Write Mutexes: sync.RWMutex + - [ ] 9.4 Memory Synchronization + - [ ] 9.5 Lazy Initialization: sync.Once + - [ ] 9.6 The Race Detector + - [ ] 9.7 Example: Concurrent Non-Blocking Cache + - [ ] 9.8 Goroutines and Threads +- [x] Chapter 10: Packages and the Go Tool + - [x] 10.1 Introduction + - [x] 10.2 Import Paths + - [x] 10.3 The Package Declaration + - [x] 10.4 Import Declarations + - [x] 10.5 Blank Imports + - [x] 10.6 Packages and Naming + - [x] 10.7 The Go Tool +- [x] Chapter 11: Testing + - [x] 11.1 The go test Tool + - [ ] 11.2 Test Functions + - [ ] 11.3 Coverage + - [ ] 11.4 Benchmark Functions + - [ ] 11.5 Profiling + - [x] 11.6 Example Functions +- [ ] Chapter 12: Reflection + - [ ] 12.1 Why Reflection? + - [ ] 12.2 reflect.Type and reflect.Value + - [ ] 12.3 Display, a Recursive Value Printer + - [ ] 12.4 Example: Encoding S-Expressions + - [ ] 12.5 Setting Variables with reflect.Value + - [ ] 12.6 Example: Decoding S-Expressions + - [ ] 12.7 Accessing Struct Field Tags + - [ ] 12.8 Displaying the Methods of a Type + - [ ] 12.9 A Word of Caution +- [x] Chapter 13: Low-Level Programming + - [x] 13.1 unsafe.Sizeof, Alignof, and Offsetof + - [x] 13.2 unsafe.Pointer + - [x] 13.3 Example: Deep Equivalence + - [x] 13.4 Calling C Code with cgo + - [x] 13.5 Another Word of Caution +- [ ] Exercise and Answer +- [ ] Errata + diff --git a/tools/TSCharacters.txt b/tools/TSCharacters.txt new file mode 100644 index 0000000..9bc2f27 --- /dev/null +++ b/tools/TSCharacters.txt @@ -0,0 +1,4179 @@ +㑮 𫝈 +㑯 㑔 +㑳 㑇 +㑶 㐹 +㒓 𠉂 +㓄 𪠟 +㓨 刾 +㔋 𪟎 +㖮 𪠵 +㗲 𠵾 +㗿 𪡛 +㘉 𠰱 +㘓 𪢌 +㘔 㗷 +㘚 㘎 +㛝 𫝦 +㜄 㚯 +㜏 㛣 +㜐 𫝧 +㜗 𡞋 +㜢 𡞱 +㜷 𡝠 +㞞 𪨊 +㟺 𪩇 +㠏 㟆 +㢗 𪪑 +㢝 𢋈 +㥮 㤘 +㦎 𢛯 +㦛 𢗓 +㦞 𪫷 +㨻 𪮃 +㩋 𪮋 +㩜 㨫 +㩳 㧐 +㩵 擜 +㪎 𪯋 +㯤 𣘐 +㰙 𣗙 +㵗 𣳆 +㵾 𪷍 +㶆 𫞛 +㷍 𤆢 +㷿 𤈷 +㸇 𤎺 +㹽 𫞣 +㺏 𤠋 +㺜 𪺻 +㻶 𪼋 +㿖 𪽮 +㿗 𤻊 +㿧 𤽯 +䀉 𥁢 +䀹 𥅴 +䁪 𥇢 +䁻 䀥 +䂎 𥎝 +䅐 𫀨 +䅳 𫀬 +䆉 𫁂 +䉑 𫁲 +䉙 𥬀 +䉬 𫂈 +䉲 𥮜 +䉶 𫁷 +䊭 𥺅 +䊷 䌶 +䊺 𫄚 +䋃 𫄜 +䋔 𫄞 +䋙 䌺 +䋚 䌻 +䋦 𫄩 +䋹 䌿 +䋻 䌾 +䋼 𫄮 +䋿 𦈓 +䌈 𦈖 +䌋 𦈘 +䌖 𦈜 +䌝 𦈟 +䌟 𦈞 +䌥 𦈠 +䌰 𦈙 +䍤 𫅅 +䍦 䍠 +䍽 𦍠 +䎙 𫅭 +䎱 䎬 +䕤 𫟕 +䕳 𦰴 +䖅 𫟑 +䗅 𫊪 +䗿 𧉞 +䙔 𫋲 +䙡 䙌 +䙱 𧜭 +䚩 𫌯 +䛄 𫍠 +䛳 𫍫 +䜀 䜧 +䜖 𫟢 +䝭 𫎧 +䝻 𧹕 +䝼 䞍 +䞈 𧹑 +䞋 𫎪 +䞓 𫎭 +䟃 𫎺 +䟆 𫎳 +䟐 𫎱 +䠆 𫏃 +䠱 𨅛 +䡐 𫟤 +䡩 𫟥 +䡵 𫟦 +䢨 𨑹 +䤤 𫟺 +䥄 𫠀 +䥇 䦂 +䥗 𫔋 +䥩 𨱖 +䥯 𫔆 +䥱 䥾 +䦘 𨸄 +䦛 䦶 +䦟 䦷 +䦯 𫔵 +䦳 𨷿 +䧢 𨸟 +䪊 𫖅 +䪏 𩏼 +䪗 𩐀 +䪘 𩏿 +䪴 𫖫 +䪾 𫖬 +䫀 𫖱 +䫂 𫖰 +䫟 𫖲 +䫴 𩖗 +䫶 𫖺 +䫻 𫗇 +䫾 𫠈 +䬓 𫗊 +䬘 𩙮 +䬝 𩙯 +䬞 𩙧 +䬧 𫗟 +䭀 𩠇 +䭃 𩠈 +䭑 𫗱 +䭔 𫗰 +䭿 𩧭 +䮄 𫠊 +䮝 𩧰 +䮞 𩨁 +䮠 𩧿 +䮫 𩨇 +䮰 𫘮 +䮳 𩨏 +䮾 𩧪 +䯀 䯅 +䯤 𩩈 +䰾 鲃 +䱀 𫚐 +䱁 𫚏 +䱙 𩾈 +䱧 𫚠 +䱬 𩾊 +䱰 𩾋 +䱷 䲣 +䱸 𫠑 +䱽 䲝 +䲁 鳚 +䲅 𫚜 +䲖 𩾂 +䲘 鳤 +䲰 𪉂 +䳜 𫛬 +䳢 𫛰 +䳤 𫛮 +䳧 𫛺 +䳫 𫛼 +䴉 鹮 +䴋 𫜅 +䴬 𪎈 +䴱 𫜒 +䴴 𪎋 +䴽 𫜔 +䵳 𪑅 +䵴 𫜙 +䶕 𫜨 +䶲 𫜳 +万 万 +丑 丑 +丟 丢 +並 并 +丰 丰 +么 么 +乾 干 乾 +亂 乱 +了 了 +于 于 +云 云 +亙 亘 +亞 亚 +仆 仆 +仇 仇 +价 价 +仿 仿 +伙 伙 +佇 伫 +佈 布 +佔 占 +余 余 +佛 佛 +佣 佣 +併 并 +來 来 +侖 仑 +侶 侣 +侷 局 +俁 俣 +係 系 +俊 俊 +俓 𠇹 +俔 伣 +俠 侠 +俥 伡 +俬 私 +修 修 +倀 伥 +倆 俩 +倈 俫 +倉 仓 +個 个 +們 们 +倖 幸 +借 借 +倫 伦 +倲 㑈 +偉 伟 +偑 㐽 +側 侧 +偵 侦 +偽 伪 +傌 㐷 +傑 杰 +傖 伧 +傘 伞 +備 备 +傢 家 +傭 佣 +傯 偬 +傳 传 +傴 伛 +債 债 +傷 伤 +傾 倾 +僂 偻 +僅 仅 +僉 佥 +僑 侨 +僕 仆 +僞 伪 +僥 侥 +僨 偾 +僱 雇 +僵 僵 +價 价 +儀 仪 +儁 俊 +儂 侬 +億 亿 +儈 侩 +儉 俭 +儎 傤 +儐 傧 +儔 俦 +儕 侪 +儘 尽 侭 +償 偿 +儣 𠆲 +優 优 +儭 𠋆 +儲 储 +儷 俪 +儸 㑩 +儺 傩 +儻 傥 +儼 俨 +兇 凶 +克 克 +兌 兑 +兒 儿 +兗 兖 +党 党 +內 内 +兩 两 +冊 册 +冑 胄 +冪 幂 +冬 冬 +准 准 +凈 净 +凌 凌 +凍 冻 +凙 𪞝 +凜 凛 +几 几 +凱 凯 +凶 凶 +出 出 +划 划 +別 别 +刪 删 +刮 刮 +制 制 +剄 刭 +則 则 +剋 克 +剎 刹 +剗 刬 +剛 刚 +剝 剥 +剮 剐 +剴 剀 +創 创 +剷 铲 +剾 𠛅 +劃 划 㓰 +劇 剧 +劉 刘 +劊 刽 +劌 刿 +劍 剑 +劏 㓥 +劑 剂 +劚 㔉 +勁 劲 +勑 𠡠 +動 动 +務 务 +勛 勋 +勝 胜 +勞 劳 +勢 势 +勣 𪟝 +勩 勚 +勱 劢 +勳 勋 +勵 励 +勸 劝 +勻 匀 +匭 匦 +匯 汇 +匱 匮 +區 区 +千 千 +升 升 +協 协 +卜 卜 +占 占 +卷 卷 +卹 恤 +卻 却 +卽 即 +厂 厂 +厘 厘 +厙 厍 +厠 厕 +厤 历 +厭 厌 +厲 厉 +厴 厣 +參 参 +叄 叁 +叢 丛 +只 只 +台 台 +叶 叶 +吁 吁 +合 合 +吊 吊 +同 同 +后 后 +向 向 +吒 咤 +吳 吴 +吶 呐 +呂 吕 +周 周 +咨 咨 +咸 咸 +咼 呙 +咽 咽 +哄 哄 +員 员 +哯 𠯟 +唄 呗 +唓 𪠳 +唚 吣 +唸 念 +問 问 +啓 启 +啞 哑 +啟 启 +啢 唡 +喂 喂 +喎 㖞 +喚 唤 +喪 丧 +喫 吃 +喬 乔 +單 单 +喲 哟 +嗆 呛 +嗇 啬 +嗊 唝 +嗎 吗 +嗚 呜 +嗩 唢 +嗰 𠮶 +嗶 哔 +嗹 𪡏 +嘆 叹 +嘍 喽 +嘓 啯 +嘔 呕 +嘖 啧 +嘗 尝 +嘜 唛 +嘩 哗 +嘪 𪡃 +嘮 唠 +嘯 啸 +嘰 叽 +嘳 𪡞 +嘵 哓 +嘸 呒 +嘺 𪡀 +嘽 啴 +噁 恶 +噅 𠯠 +噓 嘘 +噚 㖊 +噝 咝 +噞 𪡋 +噠 哒 +噥 哝 +噦 哕 +噪 噪 +噯 嗳 +噲 哙 +噴 喷 +噸 吨 +噹 当 𪠽 +嚀 咛 +嚇 吓 +嚌 哜 +嚐 尝 +嚕 噜 +嚙 啮 +嚛 𪠸 +嚥 咽 +嚦 呖 +嚧 𠰷 +嚨 咙 +嚮 向 +嚲 亸 +嚳 喾 +嚴 严 +嚶 嘤 +嚽 𪢕 +囀 啭 +囁 嗫 +囂 嚣 +囃 𠱞 +囅 冁 +囈 呓 +囉 啰 +囌 苏 +囑 嘱 +囒 𪢠 +回 回 +囪 囱 +困 困 +圇 囵 +國 国 +圍 围 +園 园 +圓 圆 +圖 图 +團 团 +圞 𪢮 +坐 坐 +垵 埯 +埡 垭 +埬 𪣆 +埰 采 +執 执 +堅 坚 +堊 垩 +堖 垴 +堚 𪣒 +堝 埚 +堯 尧 +報 报 +場 场 +塊 块 +塋 茔 +塏 垲 +塒 埘 +塗 涂 +塚 冢 +塢 坞 +塤 埙 +塵 尘 +塹 堑 +塿 𪣻 +墊 垫 +墜 坠 +墮 堕 +墰 坛 +墲 𪢸 +墳 坟 +墶 垯 +墻 墙 +墾 垦 +壇 坛 +壈 𡒄 +壋 垱 +壎 埙 +壓 压 +壗 𡋤 +壘 垒 +壙 圹 +壚 垆 +壜 坛 +壞 坏 +壟 垄 +壠 垅 +壢 坜 +壣 𪤚 +壩 坝 +壪 塆 +壯 壮 +壺 壶 +壼 壸 +壽 寿 +夠 够 +夢 梦 +夥 伙 +夸 夸 +夾 夹 +奐 奂 +奧 奥 +奩 奁 +奪 夺 +奬 奖 +奮 奋 +奸 奸 +奼 姹 +妝 妆 +姍 姗 +姜 姜 +姦 奸 +娘 娘 +娛 娱 +婁 娄 +婡 𫝫 +婦 妇 +婭 娅 +媈 𫝨 +媧 娲 +媯 妫 +媰 㛀 +媼 媪 +媽 妈 +嫋 袅 +嫗 妪 +嫵 妩 +嫺 娴 +嫻 娴 +嫿 婳 +嬀 妫 +嬃 媭 +嬇 𫝬 +嬈 娆 +嬋 婵 +嬌 娇 +嬙 嫱 +嬡 嫒 +嬣 𪥰 +嬤 嬷 +嬦 𫝩 +嬪 嫔 +嬰 婴 +嬸 婶 +嬻 𪥿 +孃 娘 +孄 𫝮 +孆 𫝭 +孇 𪥫 +孋 㛤 +孌 娈 +孎 𡠟 +孫 孙 +學 学 +孻 𡥧 +孾 𪧀 +孿 孪 +宮 宫 +家 家 +寀 采 +寠 𪧘 +寢 寝 +實 实 +寧 宁 +審 审 +寫 写 +寬 宽 +寵 宠 +寶 宝 +將 将 +專 专 +尋 寻 +對 对 +導 导 +尷 尴 +尸 尸 +局 局 +屆 届 +屍 尸 +屓 屃 +屜 屉 +屢 屡 +層 层 +屨 屦 +屩 𪨗 +屬 属 +岡 冈 +岩 岩 +峯 峰 +峴 岘 +島 岛 +峽 峡 +崍 崃 +崑 昆 +崗 岗 +崙 仑 𪨧 +崢 峥 +崬 岽 +嵐 岚 +嵗 岁 +嵼 𡶴 +嵾 㟥 +嶁 嵝 +嶄 崭 +嶇 岖 +嶈 𡺃 +嶔 嵚 +嶗 崂 +嶘 𡺄 +嶠 峤 +嶢 峣 +嶧 峄 +嶨 峃 +嶮 崄 +嶴 岙 +嶸 嵘 +嶹 𫝵 +嶺 岭 +嶼 屿 +嶽 岳 +巊 𪩎 +巋 岿 +巒 峦 +巔 巅 +巖 岩 +巗 𪨷 +巘 𪩘 +巨 巨 +巰 巯 +巹 卺 +布 布 +帘 帘 +帥 帅 +師 师 +席 席 +帳 帐 +帶 带 +幀 帧 +幃 帏 +幓 㡎 +幗 帼 +幘 帻 +幝 𪩷 +幟 帜 +幣 币 +幩 𪩸 +幫 帮 +幬 帱 +干 干 +幸 幸 +幹 干 +幺 幺 +幾 几 +广 广 +座 座 +庫 库 +庵 庵 +廁 厕 +廂 厢 +廄 厩 +廈 厦 +廎 庼 +廕 荫 +廚 厨 +廝 厮 +廟 庙 +廠 厂 +廡 庑 +廢 废 +廣 广 +廧 𪪞 +廩 廪 +廬 庐 𪪏 +廳 厅 +弒 弑 +弔 吊 +弦 弦 +弳 弪 +張 张 +強 强 +彃 𪪼 +彆 别 +彈 弹 +彌 弥 +彎 弯 +彔 录 +彙 汇 +彞 彝 +彠 彟 +彥 彦 +彩 彩 +彫 雕 +彲 彨 +彷 彷 仿 +彿 佛 +征 征 +後 后 +徑 径 +從 从 +徠 徕 +御 御 +復 复 +徵 征 徵 +徹 彻 +徿 𪫌 +志 志 +念 念 +恆 恒 +恥 耻 +悅 悦 +悞 悮 +悵 怅 +悶 闷 +悽 凄 +惡 恶 +惱 恼 +惲 恽 +惻 恻 +愈 愈 +愛 爱 +愜 惬 +愨 悫 +愴 怆 +愷 恺 +愻 𢙏 +愾 忾 +愿 愿 +慄 栗 +態 态 +慍 愠 +慘 惨 +慚 惭 +慟 恸 +慣 惯 +慤 悫 +慪 怄 +慫 怂 +慮 虑 +慳 悭 +慶 庆 +慺 㥪 +慼 戚 +慾 欲 +憂 忧 +憊 惫 +憐 怜 +憑 凭 +憒 愦 +憖 慭 +憚 惮 +憢 𢙒 +憤 愤 +憫 悯 +憮 怃 +憲 宪 +憶 忆 +憸 𪫺 +憹 𢙐 +懀 𢙓 +懇 恳 +應 应 +懌 怿 +懍 懔 +懎 𢠁 +懞 蒙 +懟 怼 +懣 懑 +懤 㤽 +懨 恹 +懲 惩 +懶 懒 +懷 怀 +懸 悬 +懺 忏 +懼 惧 +懾 慑 +戀 恋 +戇 戆 +戔 戋 +戚 戚 +戧 戗 +戩 戬 +戰 战 𢧐 +戱 戯 +戲 戏 +戶 户 +才 才 +扎 扎 +托 托 +扣 扣 +折 折 +拋 抛 +拐 拐 +拚 拚 +挂 挂 +挨 挨 +挩 捝 +挱 挲 +挽 挽 +挾 挟 +捨 舍 +捫 扪 +据 据 +捱 挨 +捲 卷 +掃 扫 +掄 抡 +掆 㧏 +掗 挜 +掙 挣 +掚 𪭵 +掛 挂 +採 采 +揀 拣 +揚 扬 +換 换 +揮 挥 +揯 搄 +損 损 +搖 摇 +搗 捣 +搜 搜 +搵 揾 +搶 抢 +摋 𢫬 +摐 𪭢 +摑 掴 +摜 掼 +摟 搂 +摯 挚 +摳 抠 +摶 抟 +摺 折 +摻 掺 +撈 捞 +撊 𪭾 +撏 挦 +撐 撑 +撓 挠 +撝 㧑 +撟 挢 +撣 掸 +撥 拨 +撧 𪮖 +撫 抚 +撲 扑 +撳 揿 +撻 挞 +撾 挝 +撿 捡 +擁 拥 +擄 掳 +擇 择 +擊 击 +擋 挡 +擓 㧟 +擔 担 +據 据 +擟 𪭧 +擠 挤 +擡 抬 +擣 捣 𢭏 +擫 𢬍 +擬 拟 +擯 摈 +擰 拧 +擱 搁 +擲 掷 +擴 扩 +擷 撷 +擺 摆 +擻 擞 +擼 撸 +擽 㧰 +擾 扰 +攄 摅 +攆 撵 +攋 𪮶 +攏 拢 +攔 拦 +攖 撄 +攙 搀 +攛 撺 +攜 携 +攝 摄 +攢 攒 +攣 挛 +攤 摊 +攪 搅 +攬 揽 +敎 教 +敓 敚 +敗 败 +敘 叙 +敵 敌 +數 数 +斂 敛 +斃 毙 +斅 𢽾 +斆 敩 +斕 斓 +斗 斗 +斬 斩 +斷 断 +斸 𣃁 +於 于 於 +旂 旗 +旣 既 +昆 昆 +昇 升 +時 时 +晉 晋 +晝 昼 +暈 晕 +暉 晖 +暗 暗 +暘 旸 +暢 畅 +暫 暂 +曄 晔 +曆 历 +曇 昙 +曉 晓 +曊 𪰶 +曏 向 +曖 暧 +曠 旷 +曥 𣆐 +曨 昽 +曬 晒 +曲 曲 +書 书 +會 会 +朥 𦛨 +朧 胧 +朮 术 +朱 朱 +朴 朴 +杆 杆 +杠 杠 +杯 杯 +杰 杰 +東 东 +杴 锨 +松 松 +板 板 +极 极 +枴 拐 +柜 柜 +柵 栅 +柺 拐 +査 查 +栗 栗 +核 核 +桱 𣐕 +桿 杆 +梁 梁 +梔 栀 +梖 𪱷 +梘 枧 +條 条 +梟 枭 +梲 棁 +棄 弃 +棊 棋 +棖 枨 +棗 枣 +棟 栋 +棡 㭎 +棧 栈 +棱 棱 +棲 栖 +棶 梾 +椏 桠 +椲 㭏 +楇 𣒌 +楊 杨 +楓 枫 +楨 桢 +業 业 +極 极 +榘 矩 +榦 干 +榪 杩 +榮 荣 +榲 榅 +榿 桤 +構 构 +槍 枪 +槓 杠 +槤 梿 +槧 椠 +槨 椁 +槫 𣏢 +槮 椮 +槳 桨 +槶 椢 +槼 椝 +樁 桩 +樂 乐 +樅 枞 +樑 梁 +樓 楼 +標 标 +樞 枢 +樠 𣗊 +樢 㭤 +樣 样 +樤 𣔌 +樧 榝 +樫 㭴 +樳 桪 +樸 朴 +樹 树 +樺 桦 +樿 椫 +橈 桡 +橋 桥 +機 机 +橢 椭 +橫 横 +橯 𣓿 +檁 檩 +檉 柽 +檔 档 +檜 桧 +檟 槚 +檢 检 +檣 樯 +檭 𣘴 +檮 梼 +檯 台 +檳 槟 +檵 𪲛 +檸 柠 +檻 槛 +檾 𦼖 +櫃 柜 +櫅 𪲎 +櫓 橹 +櫚 榈 +櫛 栉 +櫝 椟 +櫞 橼 +櫟 栎 +櫠 𪲮 +櫥 橱 +櫧 槠 +櫨 栌 +櫪 枥 +櫫 橥 +櫬 榇 +櫱 蘖 +櫳 栊 +櫸 榉 +櫺 棂 +櫻 樱 +欄 栏 +欅 榉 +欇 𪳍 +權 权 +欍 𣐤 +欏 椤 +欐 𪲔 +欑 𪴙 +欒 栾 +欓 𣗋 +欖 榄 +欘 𣚚 +欞 棂 +欲 欲 +欽 钦 +歎 叹 +歐 欧 +歟 欤 +歡 欢 +歲 岁 +歷 历 +歸 归 +歿 殁 +殘 残 +殞 殒 +殢 𣨼 +殤 殇 +殨 㱮 +殫 殚 +殭 僵 +殮 殓 +殯 殡 +殰 㱩 +殲 歼 +殺 杀 +殻 壳 +殼 壳 +毀 毁 +毆 殴 +毊 𪵑 +毿 毵 +氂 牦 +氈 毡 +氌 氇 +氣 气 +氫 氢 +氬 氩 +氭 𣱝 +氳 氲 +氾 泛 +汎 泛 +汙 污 +決 决 +沈 沈 沉 +沒 没 +沖 冲 +況 况 +泛 泛 +泝 溯 +注 注 +洩 泄 +洶 汹 +浹 浃 +涂 涂 +涇 泾 +涌 涌 +涗 涚 +涼 凉 +淀 淀 +淒 凄 +淚 泪 +淥 渌 +淨 净 +淩 凌 +淪 沦 +淵 渊 +淶 涞 +淺 浅 +渙 涣 +減 减 +渢 沨 +渦 涡 +測 测 +游 游 +渾 浑 +湊 凑 +湋 𣲗 +湞 浈 +湧 涌 +湯 汤 +溈 沩 +準 准 +溝 沟 +溡 𪶄 +溫 温 +溮 浉 +溳 涢 +溼 湿 +滄 沧 +滅 灭 +滌 涤 +滎 荥 +滙 汇 +滬 沪 +滯 滞 +滲 渗 +滷 卤 +滸 浒 +滻 浐 +滾 滚 +滿 满 +漁 渔 +漊 溇 +漓 漓 +漚 沤 +漢 汉 +漣 涟 +漬 渍 +漲 涨 +漵 溆 +漸 渐 +漿 浆 +潁 颍 +潑 泼 +潔 洁 +潕 𣲘 +潙 沩 +潚 㴋 +潛 潜 +潣 𫞗 +潤 润 +潯 浔 +潰 溃 +潷 滗 +潿 涠 +澀 涩 +澅 𣶩 +澆 浇 +澇 涝 +澐 沄 +澗 涧 +澠 渑 +澤 泽 +澦 滪 +澩 泶 +澬 𫞚 +澮 浍 +澱 淀 +澾 㳠 +濁 浊 +濃 浓 +濄 㳡 +濆 𣸣 +濕 湿 +濘 泞 +濚 溁 +濛 蒙 +濜 浕 +濟 济 +濤 涛 +濧 㳔 +濫 滥 +濰 潍 +濱 滨 +濺 溅 +濼 泺 +濾 滤 +濿 𪵱 +瀂 澛 +瀃 𣽷 +瀅 滢 +瀆 渎 +瀇 㲿 +瀉 泻 +瀋 沈 渖 +瀏 浏 +瀕 濒 +瀘 泸 +瀝 沥 +瀟 潇 +瀠 潆 +瀦 潴 +瀧 泷 +瀨 濑 +瀰 弥 㳽 +瀲 潋 +瀾 澜 +灃 沣 +灄 滠 +灍 𫞝 +灑 洒 +灒 𪷽 +灕 漓 +灘 滩 +灙 𣺼 +灝 灏 +灡 㳕 +灣 湾 +灤 滦 +灧 滟 +灩 滟 +災 灾 +為 为 +烏 乌 +烴 烃 +無 无 +煇 𪸩 +煉 炼 +煒 炜 +煙 烟 +煢 茕 +煥 焕 +煩 烦 +煬 炀 +煱 㶽 +熂 𪸕 +熅 煴 +熉 𤈶 +熌 𤇄 +熏 熏 +熒 荧 +熓 𤆡 +熗 炝 +熚 𤇹 +熡 𤋏 +熱 热 +熲 颎 +熾 炽 +燁 烨 +燈 灯 +燉 炖 +燒 烧 +燙 烫 +燜 焖 +營 营 +燦 灿 +燬 毁 +燭 烛 +燴 烩 +燶 㶶 +燻 熏 +燼 烬 +燾 焘 +爃 𫞡 +爄 𤇃 +爇 𦶟 +爍 烁 +爐 炉 +爖 𤇭 +爛 烂 +爥 𪹳 +爧 𫞠 +爭 争 +爲 为 +爺 爷 +爾 尔 +牀 床 +牆 墙 +牘 牍 +牴 牴 抵 +牽 牵 +犖 荦 +犛 牦 +犞 𪺭 +犢 犊 +犧 牺 +狀 状 +狹 狭 +狽 狈 +猌 𪺽 +猙 狰 +猶 犹 +猻 狲 +獁 犸 +獃 呆 +獄 狱 +獅 狮 +獊 𪺷 +獎 奖 +獨 独 +獩 𤞃 +獪 狯 +獫 猃 +獮 狝 +獰 狞 +獱 㺍 +獲 获 +獵 猎 +獷 犷 +獸 兽 +獺 獭 +獻 献 +獼 猕 +玀 猡 +玁 𤞤 +珼 𫞥 +現 现 +琱 雕 +琺 珐 +琿 珲 +瑋 玮 +瑒 玚 +瑣 琐 +瑤 瑶 +瑩 莹 +瑪 玛 +瑲 玱 +瑻 𪻲 +瑽 𪻐 +璉 琏 +璊 𫞩 +璝 𪻺 +璡 琎 +璣 玑 +璦 瑷 +璫 珰 +璯 㻅 +環 环 +璵 玙 +璸 瑸 +璼 𫞨 +璽 玺 +璾 𫞦 +瓄 𪻨 +瓊 琼 +瓏 珑 +瓔 璎 +瓕 𤦀 +瓚 瓒 +瓛 𤩽 +瓮 瓮 +甌 瓯 +甕 瓮 +產 产 +産 产 +甦 苏 +甯 宁 +畝 亩 +畢 毕 +畫 画 划 +異 异 +畵 画 +當 当 +畼 𪽈 +疇 畴 +疊 叠 +症 症 +痙 痉 +痠 酸 +痮 𪽪 +痾 疴 +瘂 痖 +瘋 疯 +瘍 疡 +瘓 痪 +瘞 瘗 +瘡 疮 +瘧 疟 +瘮 瘆 +瘱 𪽷 +瘲 疭 +瘺 瘘 +瘻 瘘 +療 疗 +癆 痨 +癇 痫 +癉 瘅 +癐 𤶊 +癒 愈 +癘 疠 +癟 瘪 +癡 痴 +癢 痒 +癤 疖 +癥 症 +癧 疬 +癩 癞 +癬 癣 +癭 瘿 +癮 瘾 +癰 痈 +癱 瘫 +癲 癫 +發 发 +皁 皂 +皚 皑 +皟 𤾀 +皰 疱 +皸 皲 +皺 皱 +盃 杯 +盜 盗 +盞 盏 +盡 尽 +監 监 +盤 盘 +盧 卢 +盨 𪾔 +盪 荡 +眝 𪾣 +眞 真 +眥 眦 +眾 众 +睍 𪾢 +睏 困 +睜 睁 +睞 睐 +睪 睾 睪 +瞘 眍 +瞜 䁖 +瞞 瞒 +瞤 𥆧 +瞭 瞭 了 +瞶 瞆 +瞼 睑 +矇 蒙 +矉 𪾸 +矑 𪾦 +矓 眬 +矚 瞩 +矩 矩 +矯 矫 +硃 朱 +硜 硁 +硤 硖 +硨 砗 +确 确 +硯 砚 +碕 埼 +碙 𥐻 +碩 硕 +碭 砀 +碸 砜 +確 确 +碼 码 +碽 䂵 +磑 硙 +磚 砖 +磠 硵 +磣 碜 +磧 碛 +磯 矶 +磽 硗 +磾 䃅 +礄 硚 +礆 硷 +礎 础 +礒 𥐟 +礙 碍 +礦 矿 +礪 砺 +礫 砾 +礬 矾 +礮 𪿫 +礱 砻 +祇 祇 只 +祕 秘 +祘 祘 +祿 禄 +禍 祸 +禎 祯 +禕 祎 +禡 祃 +禦 御 +禪 禅 +禮 礼 +禰 祢 +禱 祷 +禿 秃 +私 私 +秈 籼 +秋 秋 +种 种 +稅 税 +稈 秆 +稏 䅉 +稜 棱 +稟 禀 +種 种 +稱 称 +穀 谷 +穇 䅟 +穌 稣 +積 积 +穎 颖 +穗 穗 +穠 秾 +穡 穑 +穢 秽 +穩 稳 +穫 获 +穭 穞 +窩 窝 +窪 洼 +窮 穷 +窯 窑 +窵 窎 +窶 窭 +窺 窥 +竄 窜 +竅 窍 +竇 窦 +竈 灶 +竊 窃 +竚 𥩟 +竪 竖 +竱 𫁟 +競 竞 +筆 笔 +筍 笋 +筑 筑 +筧 笕 +筴 䇲 +箇 个 +箋 笺 +箏 筝 +節 节 +範 范 +築 筑 +篋 箧 +篔 筼 +篘 𥬠 +篠 筿 +篤 笃 +篩 筛 +篳 筚 +篸 𥮾 +簀 箦 +簂 𫂆 +簍 篓 +簑 蓑 +簞 箪 +簡 简 +簢 𫂃 +簣 篑 +簫 箫 +簹 筜 +簽 签 +簾 帘 +籃 篮 +籅 𥫣 +籋 𥬞 +籌 筹 +籔 䉤 +籙 箓 +籛 篯 +籜 箨 +籟 籁 +籠 笼 +籤 签 +籩 笾 +籪 簖 +籬 篱 +籮 箩 +籲 吁 +粵 粤 +糉 粽 +糝 糁 +糞 粪 +糧 粮 +糰 团 +糲 粝 +糴 籴 +糶 粜 +糹 纟 +糺 𫄙 +系 系 +糾 纠 +紀 纪 +紂 纣 +約 约 +紅 红 +紆 纡 +紇 纥 +紈 纨 +紉 纫 +紋 纹 +納 纳 +紐 纽 +紓 纾 +純 纯 +紕 纰 +紖 纼 +紗 纱 +紘 纮 +紙 纸 +級 级 +紛 纷 +紜 纭 +紝 纴 +紟 𫄛 +紡 纺 +紬 䌷 +紮 扎 +累 累 +細 细 +紱 绂 +紲 绁 +紳 绅 +紵 纻 +紹 绍 +紺 绀 +紼 绋 +紿 绐 +絀 绌 +絁 𫄟 +終 终 +絃 弦 +組 组 +絅 䌹 +絆 绊 +絍 𫟃 +絎 绗 +結 结 +絕 绝 +絙 𫄠 +絛 绦 +絝 绔 +絞 绞 +絡 络 +絢 绚 +絥 𫄢 +給 给 +絧 𫄡 +絨 绒 +絰 绖 +統 统 +絲 丝 +絳 绛 +絶 绝 +絹 绢 +絺 𫄨 +綀 𦈌 +綁 绑 +綃 绡 +綆 绠 +綇 𦈋 +綈 绨 +綉 绣 +綋 𫟄 +綌 绤 +綏 绥 +綐 䌼 +綑 捆 +經 经 +綖 𫄧 +綜 综 +綞 缍 +綟 𫄫 +綠 绿 +綡 𫟅 +綢 绸 +綣 绻 +綫 线 +綬 绶 +維 维 +綯 绹 +綰 绾 +綱 纲 +網 网 +綳 绷 +綴 缀 +綵 彩 䌽 +綸 纶 +綹 绺 +綺 绮 +綻 绽 +綽 绰 +綾 绫 +綿 绵 +緄 绲 +緇 缁 +緊 紧 +緋 绯 +緍 𦈏 +緑 绿 +緒 绪 +緓 绬 +緔 绱 +緗 缃 +緘 缄 +緙 缂 +線 线 缐 +緝 缉 +緞 缎 +緟 𫟆 +締 缔 +緡 缗 +緣 缘 +緤 𫄬 +緦 缌 +編 编 +緩 缓 +緬 缅 +緮 𫄭 +緯 纬 +緰 𦈕 +緱 缑 +緲 缈 +練 练 +緶 缏 +緷 𦈉 +緸 𦈑 +緹 缇 +緻 致 +緼 缊 +縈 萦 +縉 缙 +縊 缢 +縋 缒 +縍 𫄰 +縎 𦈔 +縐 绉 +縑 缣 +縕 缊 +縗 缞 +縛 缚 +縝 缜 +縞 缟 +縟 缛 +縣 县 +縧 绦 +縫 缝 +縬 𦈚 +縭 缡 +縮 缩 +縰 𫄳 +縱 纵 +縲 缧 +縳 䌸 +縴 纤 +縵 缦 +縶 絷 +縷 缕 +縸 𫄲 +縹 缥 +縺 𦈐 +總 总 +績 绩 +繂 𫄴 +繃 绷 +繅 缫 +繆 缪 +繈 𫄶 +繏 𦈝 +繐 穗 +繒 缯 +繓 𦈛 +織 织 +繕 缮 +繚 缭 +繞 绕 +繟 𦈎 +繡 绣 +繢 缋 +繨 𫄤 +繩 绳 +繪 绘 +繫 系 +繬 𫄱 +繭 茧 +繮 缰 +繯 缳 +繰 缲 +繳 缴 +繶 𫄷 +繷 𫄣 +繸 䍁 +繹 绎 +繻 𦈡 +繼 继 +繽 缤 +繾 缱 +繿 䍀 +纁 𫄸 +纇 颣 +纈 缬 +纊 纩 +續 续 +纍 累 +纏 缠 +纓 缨 +纔 才 +纖 纤 +纗 𫄹 +纘 缵 +纚 𫄥 +纜 缆 +缽 钵 +罃 䓨 +罈 坛 +罌 罂 +罎 坛 +罰 罚 +罵 骂 +罷 罢 +羅 罗 +羆 罴 +羈 羁 +羋 芈 +羣 群 +羥 羟 +羨 羡 +義 义 +羵 𫅗 +羶 膻 +習 习 +翬 翚 +翹 翘 +翽 翙 +耬 耧 +耮 耢 +聖 圣 +聞 闻 +聯 联 +聰 聪 +聲 声 +聳 耸 +聵 聩 +聶 聂 +職 职 +聹 聍 +聻 𫆏 +聽 听 +聾 聋 +肅 肃 +肴 肴 +胜 胜 +胡 胡 +脅 胁 +脈 脉 +脛 胫 +脣 唇 +脥 𣍰 +脩 修 +脫 脱 +脹 胀 +腊 腊 +腌 腌 +腎 肾 +腖 胨 +腡 脶 +腦 脑 +腪 𣍯 +腫 肿 +腳 脚 +腸 肠 +膃 腽 +膕 腘 +膚 肤 +膞 䏝 +膠 胶 +膢 𦝼 +膩 腻 +膹 𪱥 +膽 胆 +膾 脍 +膿 脓 +臉 脸 +臍 脐 +臏 膑 +臗 𣎑 +臘 腊 +臚 胪 +臟 脏 +臠 脔 +臢 臜 +臥 卧 +臨 临 +致 致 +臺 台 +與 与 +興 兴 +舉 举 +舊 旧 +舍 舍 +舘 馆 +艙 舱 +艣 𫇛 +艤 舣 +艦 舰 +艫 舻 +艱 艰 +艷 艳 +芻 刍 +苧 苎 +苹 苹 +范 范 +茲 兹 +荊 荆 +荐 荐 +莊 庄 +莖 茎 +莢 荚 +莧 苋 +菕 芲 +華 华 +菴 庵 +菸 烟 +萇 苌 +萊 莱 +萬 万 +萴 荝 +萵 莴 +葉 叶 +葒 荭 +著 著 +葝 𫈎 +葤 荮 +葦 苇 +葯 药 +葷 荤 +蒍 𫇭 +蒐 搜 +蒓 莼 +蒔 莳 +蒕 蒀 +蒙 蒙 +蒞 莅 +蒭 𫇴 +蒼 苍 +蓀 荪 +蓆 席 +蓋 盖 +蓧 𦰏 +蓮 莲 +蓯 苁 +蓴 莼 +蓽 荜 +蔑 蔑 +蔔 卜 +蔘 参 +蔞 蒌 +蔣 蒋 +蔥 葱 +蔦 茑 +蔭 荫 +蔯 𫈟 +蔿 𫇭 +蕁 荨 +蕆 蒇 +蕎 荞 +蕒 荬 +蕓 芸 +蕕 莸 +蕘 荛 +蕝 𫈵 +蕢 蒉 +蕩 荡 +蕪 芜 +蕭 萧 +蕳 𫈉 +蕷 蓣 +蕽 𫇽 +薀 蕰 +薆 𫉁 +薈 荟 +薊 蓟 +薌 芗 +薑 姜 +薔 蔷 +薘 荙 +薟 莶 +薦 荐 +薩 萨 +薰 薰 熏 +薳 䓕 +薴 苧 +薵 䓓 +薹 苔 薹 +薺 荠 +藉 藉 借 +藍 蓝 +藎 荩 +藝 艺 +藥 药 +藪 薮 +藭 䓖 +藴 蕴 +藶 苈 +藷 𫉄 +藹 蔼 +藺 蔺 +蘀 萚 +蘄 蕲 +蘆 芦 +蘇 苏 +蘊 蕴 +蘋 苹 蘋 +蘚 藓 +蘞 蔹 +蘟 𦻕 +蘢 茏 +蘭 兰 +蘺 蓠 +蘿 萝 +虆 蔂 +處 处 +虛 虚 +虜 虏 +號 号 +虧 亏 +虫 虫 +虯 虬 +蛺 蛱 +蛻 蜕 +蜆 蚬 +蜡 蜡 +蝕 蚀 +蝟 猬 +蝦 虾 +蝨 虱 +蝸 蜗 +螄 蛳 +螞 蚂 +螢 萤 +螮 䗖 +螻 蝼 +螿 螀 +蟂 𫋇 +蟄 蛰 +蟈 蝈 +蟎 螨 +蟘 𫋌 +蟜 𫊸 +蟣 虮 +蟬 蝉 +蟯 蛲 +蟲 虫 +蟳 𫊻 +蟶 蛏 +蟻 蚁 +蠀 𧏗 +蠁 蚃 +蠅 蝇 +蠆 虿 +蠍 蝎 +蠐 蛴 +蠑 蝾 +蠔 蚝 +蠙 𧏖 +蠟 蜡 +蠣 蛎 +蠦 𫊮 +蠨 蟏 +蠱 蛊 +蠶 蚕 +蠻 蛮 +蠾 𧑏 +衆 众 +衊 蔑 +術 术 +衕 同 +衚 胡 +衛 卫 +衝 冲 +表 表 +衹 衹 只 +袞 衮 +裊 袅 +裏 里 +補 补 +裝 装 +裡 里 +製 制 +複 复 +褌 裈 +褘 袆 +褲 裤 +褳 裢 +褸 褛 +褻 亵 +襀 𫌀 +襆 幞 +襇 裥 +襉 裥 +襏 袯 +襓 𫋹 +襖 袄 +襗 𫋷 +襘 𫋻 +襝 裣 +襠 裆 +襤 褴 +襪 袜 +襬 摆 䙓 +襯 衬 +襰 𧝝 +襲 袭 +襴 襕 +襵 𫌇 +覆 覆 复 +覈 核 +見 见 +覎 觃 +規 规 +覓 觅 +視 视 +覘 觇 +覛 𫌪 +覡 觋 +覥 觍 +覦 觎 +親 亲 +覬 觊 +覯 觏 +覲 觐 +覷 觑 +覹 𫌭 +覺 觉 +覼 𫌨 +覽 览 +覿 觌 +觀 观 +觴 觞 +觶 觯 +觸 触 +訁 讠 +訂 订 +訃 讣 +計 计 +訊 讯 +訌 讧 +討 讨 +訐 讦 +訑 𫍙 +訒 讱 +訓 训 +訕 讪 +訖 讫 +託 托 讬 +記 记 +訛 讹 +訜 𫍛 +訝 讶 +訞 𫍚 +訟 讼 +訢 䜣 +訣 诀 +訥 讷 +訨 𫟞 +訩 讻 +訪 访 +設 设 +許 许 +訴 诉 +訶 诃 +診 诊 +註 注 +証 证 +詀 𧮪 +詁 诂 +詆 诋 +詊 𫟟 +詎 讵 +詐 诈 +詑 𫍡 +詒 诒 +詓 𫍜 +詔 诏 +評 评 +詖 诐 +詗 诇 +詘 诎 +詛 诅 +詞 词 +詠 咏 +詡 诩 +詢 询 +詣 诣 +試 试 +詩 诗 +詫 诧 +詬 诟 +詭 诡 +詮 诠 +詰 诘 +話 话 +該 该 +詳 详 +詵 诜 +詷 𫍣 +詼 诙 +詿 诖 +誂 𫍥 +誄 诔 +誅 诛 +誆 诓 +誇 夸 +誋 𫍪 +誌 志 +認 认 +誑 诳 +誒 诶 +誕 诞 +誘 诱 +誚 诮 +語 语 +誠 诚 +誡 诫 +誣 诬 +誤 误 +誥 诰 +誦 诵 +誨 诲 +說 说 +誫 𫍨 +説 说 +誰 谁 +課 课 +誳 𫍮 +誴 𫟡 +誶 谇 +誷 𫍬 +誹 诽 +誺 𫍧 +誼 谊 +誾 訚 +調 调 +諂 谄 +諄 谆 +談 谈 +諉 诿 +請 请 +諍 诤 +諏 诹 +諑 诼 +諒 谅 +論 论 +諗 谂 +諛 谀 +諜 谍 +諝 谞 +諞 谝 +諡 谥 +諢 诨 +諣 𫍩 +諤 谔 +諥 𫍳 +諦 谛 +諧 谐 +諫 谏 𫍝 +諭 谕 +諮 咨 谘 +諯 𫍱 +諰 𫍰 +諱 讳 +諳 谙 +諴 𫍯 +諶 谌 +諷 讽 +諸 诸 +諺 谚 +諼 谖 +諾 诺 +謀 谋 +謁 谒 +謂 谓 +謄 誊 +謅 诌 +謆 𫍸 +謉 𫍷 +謊 谎 +謎 谜 +謏 𫍲 +謐 谧 +謔 谑 +謖 谡 +謗 谤 +謙 谦 +謚 谥 +講 讲 +謝 谢 +謠 谣 +謡 谣 +謨 谟 +謫 谪 +謬 谬 +謭 谫 +謯 𫍹 +謱 𫍴 +謳 讴 +謸 𫍵 +謹 谨 +謾 谩 +譁 哗 +譂 𫟠 +譅 䜧 +譆 𫍻 +證 证 +譊 𫍢 +譎 谲 +譏 讥 +譑 𫍤 +譖 谮 +識 识 +譙 谯 +譚 谭 +譜 谱 +譞 𫍽 +譟 噪 +譨 𫍦 +譫 谵 +譭 毁 +譯 译 +議 议 +譴 谴 +護 护 +譸 诪 +譽 誉 +譾 谫 𫍿 +讀 读 +讅 谉 +變 变 +讋 詟 +讌 䜩 +讎 雠 +讒 谗 +讓 让 +讕 谰 +讖 谶 +讚 赞 +讜 谠 +讞 谳 +谷 谷 +豈 岂 +豎 竖 +豐 丰 +豔 艳 +豬 猪 +豵 𫎆 +豶 豮 +貓 猫 +貗 𫎌 +貙 䝙 +貝 贝 +貞 贞 +貟 贠 +負 负 +財 财 +貢 贡 +貧 贫 +貨 货 +販 贩 +貪 贪 +貫 贯 +責 责 +貯 贮 +貰 贳 +貲 赀 +貳 贰 +貴 贵 +貶 贬 +買 买 𧹒 +貸 贷 +貺 贶 +費 费 +貼 贴 +貽 贻 +貿 贸 +賀 贺 +賁 贲 +賂 赂 +賃 赁 +賄 贿 +賅 赅 +資 资 +賈 贾 +賊 贼 +賑 赈 +賒 赊 +賓 宾 +賕 赇 +賙 赒 +賚 赉 +賜 赐 +賝 𫎩 +賞 赏 +賟 𧹖 +賠 赔 +賡 赓 +賢 贤 +賣 卖 +賤 贱 +賦 赋 +賧 赕 +質 质 +賫 赍 +賬 账 +賭 赌 +賰 䞐 +賴 赖 +賵 赗 +賺 赚 +賻 赙 +購 购 +賽 赛 +賾 赜 +贃 𧹗 +贄 贽 +贅 赘 +贇 赟 +贈 赠 +贉 𫎫 +贊 赞 +贋 赝 +贍 赡 +贏 赢 +贐 赆 +贑 𫎬 +贓 赃 +贔 赑 +贖 赎 +贗 赝 +贚 𫎦 +贛 赣 +贜 赃 +赬 赪 +趕 赶 +趙 赵 +趨 趋 +趲 趱 +跡 迹 +踊 踊 +踐 践 +踰 逾 +踴 踊 +蹌 跄 +蹔 𫏐 +蹕 跸 +蹟 迹 +蹣 蹒 +蹤 踪 +蹳 𫏆 +蹺 跷 +蹻 𫏋 +躂 跶 +躉 趸 +躊 踌 +躋 跻 +躍 跃 +躎 䟢 +躑 踯 +躒 跞 +躓 踬 +躕 蹰 +躘 𨀁 +躚 跹 +躝 𨅬 +躡 蹑 +躥 蹿 +躦 躜 +躪 躏 +軀 躯 +軉 𨉗 +車 车 +軋 轧 +軌 轨 +軍 军 +軏 𫐄 +軑 轪 +軒 轩 +軔 轫 +軕 𫐅 +軗 𨐅 +軛 轭 +軜 𫐇 +軟 软 +軤 轷 +軨 𫐉 +軫 轸 +軬 𫐊 +軲 轱 +軷 𫐈 +軸 轴 +軹 轵 +軺 轺 +軻 轲 +軼 轶 +軾 轼 +軿 𫐌 +較 较 +輄 𨐈 +輅 辂 +輇 辁 +輈 辀 +載 载 +輊 轾 +輋 𪨶 +輒 辄 +輓 挽 +輔 辅 +輕 轻 +輖 𫐏 +輗 𫐐 +輛 辆 +輜 辎 +輝 辉 +輞 辋 +輟 辍 +輢 𫐎 +輥 辊 +輦 辇 +輨 𫐑 +輩 辈 +輪 轮 +輬 辌 +輮 𫐓 +輯 辑 +輳 辏 +輷 𫐒 +輸 输 +輻 辐 +輼 辒 +輾 辗 +輿 舆 +轀 辒 +轂 毂 +轄 辖 +轅 辕 +轆 辘 +轇 𫐖 +轉 转 +轊 𫐕 +轍 辙 +轎 轿 +轐 𫐗 +轔 辚 +轗 𫐘 +轟 轰 +轠 𫐙 +轡 辔 +轢 轹 +轣 𫐆 +轤 轳 +辟 辟 +辦 办 +辭 辞 +辮 辫 +辯 辩 +農 农 +迴 回 +适 适 +逕 迳 +這 这 +連 连 +週 周 +進 进 +遊 游 +運 运 +過 过 +達 达 +違 违 +遙 遥 +遜 逊 +遞 递 +遠 远 +遡 溯 +適 适 +遱 𫐷 +遲 迟 +遷 迁 +選 选 +遺 遗 +遼 辽 +邁 迈 +還 还 +邇 迩 +邊 边 +邏 逻 +邐 逦 +郁 郁 +郟 郏 +郵 邮 +鄆 郓 +鄉 乡 +鄒 邹 +鄔 邬 +鄖 郧 +鄟 𫑘 +鄧 邓 +鄭 郑 +鄰 邻 +鄲 郸 +鄳 𫑡 +鄴 邺 +鄶 郐 +鄺 邝 +酇 酂 +酈 郦 +酸 酸 +醃 腌 +醖 酝 +醜 丑 +醞 酝 +醟 蒏 +醣 糖 +醫 医 +醬 酱 +醱 酦 +醶 𫑷 +釀 酿 +釁 衅 +釃 酾 +釅 酽 +采 采 +釋 释 +里 里 +釐 厘 +釒 钅 +釓 钆 +釔 钇 +釕 钌 +釗 钊 +釘 钉 +釙 钋 +釚 𫟲 +針 针 +釟 𫓥 +釣 钓 +釤 钐 +釦 扣 +釧 钏 +釨 𫓦 +釩 钒 +釲 𫟳 +釳 𨰿 +釵 钗 +釷 钍 +釹 钕 +釺 钎 +釾 䥺 +鈀 钯 +鈁 钫 +鈃 钘 +鈄 钭 +鈅 钥 +鈆 𫓪 +鈇 𫓧 +鈈 钚 +鈉 钠 +鈋 𨱂 +鈍 钝 +鈎 钩 +鈐 钤 +鈑 钣 +鈒 钑 +鈔 钞 +鈕 钮 纽 +鈖 𫟴 +鈗 𫟵 +鈛 𫓨 +鈞 钧 +鈠 𨱁 +鈡 钟 +鈣 钙 +鈥 钬 +鈦 钛 +鈧 钪 +鈮 铌 +鈯 𨱄 +鈰 铈 +鈲 𨱃 +鈳 钶 +鈴 铃 +鈷 钴 +鈸 钹 +鈹 铍 +鈺 钰 +鈽 钸 +鈾 铀 +鈿 钿 +鉀 钾 +鉁 𨱅 +鉅 巨 钜 +鉆 钻 +鉈 铊 +鉉 铉 +鉋 铇 +鉍 铋 +鉑 铂 +鉔 𫓬 +鉕 钷 +鉗 钳 +鉚 铆 +鉛 铅 +鉝 𫟷 +鉞 钺 +鉠 𫓭 +鉢 钵 +鉤 钩 +鉦 钲 +鉬 钼 +鉭 钽 +鉳 锫 +鉶 铏 +鉷 𫟹 +鉸 铰 +鉺 铒 +鉻 铬 +鉽 𫟸 +鉾 𫓴 +鉿 铪 +銀 银 +銁 𫓲 +銂 𫟻 +銃 铳 +銅 铜 +銈 𫓯 +銊 𫓰 +銍 铚 +銏 𫟶 +銑 铣 +銓 铨 +銖 铢 +銘 铭 +銚 铫 +銛 铦 +銜 衔 +銠 铑 +銣 铷 +銥 铱 +銦 铟 +銨 铵 +銩 铥 +銪 铕 +銫 铯 +銬 铐 +銱 铞 +銳 锐 +銶 𨱇 +銷 销 +銹 锈 +銻 锑 +銼 锉 +鋁 铝 +鋂 镅 +鋃 锒 +鋅 锌 +鋇 钡 +鋉 𨱈 +鋌 铤 +鋏 铗 +鋒 锋 +鋗 𫓶 +鋙 铻 +鋝 锊 +鋟 锓 +鋠 𫓵 +鋣 铘 +鋤 锄 +鋥 锃 +鋦 锔 +鋨 锇 +鋩 铓 +鋪 铺 +鋭 锐 +鋮 铖 +鋯 锆 +鋰 锂 +鋱 铽 +鋶 锍 +鋸 锯 +鋼 钢 +錁 锞 +錂 𨱋 +錄 录 +錆 锖 +錇 锫 +錈 锩 +錏 铔 +錐 锥 +錒 锕 +錕 锟 +錘 锤 +錙 锱 +錚 铮 +錛 锛 +錜 𫓻 +錝 𫓽 +錟 锬 +錠 锭 +錡 锜 +錢 钱 +錤 𫓹 +錥 𫓾 +錦 锦 +錨 锚 +錩 锠 +錫 锡 +錮 锢 +錯 错 +録 录 +錳 锰 +錶 表 +錸 铼 +錼 镎 +錽 𫓸 +鍀 锝 +鍁 锨 +鍃 锪 +鍄 𨱉 +鍅 钫 +鍆 钔 +鍇 锴 +鍈 锳 +鍉 𫔂 +鍊 炼 链 𫔀 +鍋 锅 +鍍 镀 +鍒 𫔄 +鍔 锷 +鍘 铡 +鍚 钖 +鍛 锻 +鍠 锽 +鍤 锸 +鍥 锲 +鍩 锘 +鍬 锹 +鍮 𨱎 +鍰 锾 +鍵 键 +鍶 锶 +鍺 锗 +鍼 针 +鍾 钟 锺 +鎂 镁 +鎄 锿 +鎇 镅 +鎈 𫟿 +鎊 镑 +鎌 镰 +鎍 𫔅 +鎔 镕 +鎖 锁 +鎘 镉 +鎙 𫔈 +鎚 锤 +鎛 镈 +鎝 𨱏 +鎞 𫔇 +鎡 镃 +鎢 钨 +鎣 蓥 +鎦 镏 +鎧 铠 +鎩 铩 +鎪 锼 +鎬 镐 +鎭 镇 +鎮 镇 +鎯 𨱍 +鎰 镒 +鎲 镋 +鎳 镍 +鎵 镓 +鎷 𨰾 +鎸 镌 +鎿 镎 +鏃 镞 +鏆 𨱌 +鏇 镟 +鏈 链 +鏉 𨱒 +鏌 镆 +鏍 镙 +鏐 镠 +鏑 镝 +鏗 铿 +鏘 锵 +鏚 戚 +鏜 镗 +鏝 镘 +鏞 镛 +鏟 铲 +鏡 镜 +鏢 镖 +鏤 镂 +鏥 𫔊 +鏦 𫓩 +鏨 錾 +鏰 镚 +鏵 铧 +鏷 镤 +鏹 镪 +鏺 䥽 +鏽 锈 +鏾 𫔌 +鐃 铙 +鐄 𨱑 +鐇 𫔍 +鐈 𫓱 +鐋 铴 +鐍 𫔎 +鐎 𨱓 +鐏 𨱔 +鐐 镣 +鐒 铹 +鐓 镦 +鐔 镡 +鐗 锏 +鐘 钟 +鐙 镫 +鐝 镢 +鐠 镨 +鐥 䦅 +鐦 锎 +鐧 锏 +鐨 镄 +鐪 𫓺 +鐫 镌 +鐮 镰 +鐯 䦃 +鐲 镯 +鐳 镭 +鐵 铁 +鐶 镮 +鐸 铎 +鐺 铛 +鐼 𫔁 +鐽 𫟼 +鐿 镱 +鑀 锿 +鑄 铸 +鑉 𫠁 +鑊 镬 +鑌 镔 +鑑 鉴 +鑒 鉴 +鑔 镲 +鑕 锧 +鑞 镴 +鑠 铄 +鑣 镳 +鑥 镥 +鑭 镧 +鑰 钥 +鑱 镵 +鑲 镶 +鑴 𫔔 +鑷 镊 +鑹 镩 +鑼 锣 +鑽 钻 +鑾 銮 +鑿 凿 +钁 镢 䦆 +钂 镋 +镟 旋 +長 长 +門 门 +閂 闩 +閃 闪 +閆 闫 +閈 闬 +閉 闭 +開 开 𫔭 +閌 闶 +閍 𨸂 +閎 闳 +閏 闰 +閐 𨸃 +閑 闲 +閒 闲 𫔮 +間 间 +閔 闵 +閗 𫔯 +閘 闸 +閝 𫠂 +閞 𫔰 +閡 阂 +閣 阁 +閤 合 +閥 阀 +閨 闺 +閩 闽 +閫 阃 +閬 阆 +閭 闾 +閱 阅 +閲 阅 +閵 𫔴 +閶 阊 +閹 阉 +閻 阎 +閼 阏 +閽 阍 +閾 阈 +閿 阌 +闃 阒 +闆 板 +闇 暗 +闈 闱 +闊 阔 +闋 阕 +闌 阑 +闍 阇 +闐 阗 +闑 𫔶 +闒 阘 +闓 闿 +闔 阖 +闕 阙 +闖 闯 +關 关 +闞 阚 +闠 阓 +闡 阐 +闢 辟 +闤 阛 +闥 闼 +阪 阪 坂 +陘 陉 +陝 陕 +陞 升 +陣 阵 +陰 阴 +陳 陈 +陸 陆 +陽 阳 +隉 陧 +隊 队 +階 阶 +隕 陨 +際 际 +隨 随 +險 险 +隯 陦 +隱 隐 +隴 陇 +隸 隶 +隻 只 +雇 雇 +雋 隽 +雕 雕 +雖 虽 +雙 双 +雛 雏 +雜 杂 +雞 鸡 +離 离 +難 难 +雲 云 +電 电 +霢 霡 +霣 𫕥 +霧 雾 +霼 𪵣 +霽 霁 +靂 雳 +靄 霭 +靆 叇 +靈 灵 +靉 叆 +靚 靓 +靜 静 +靝 靔 +面 面 +靦 腼 䩄 +靧 𫖃 +靨 靥 +鞀 鼗 +鞏 巩 +鞝 绱 +鞦 秋 +鞽 鞒 +鞾 𫖇 +韁 缰 +韃 鞑 +韆 千 +韉 鞯 +韋 韦 +韌 韧 +韍 韨 +韓 韩 +韙 韪 +韚 𫠅 +韛 𫖔 +韜 韬 +韝 鞲 𫖕 +韞 韫 +韠 𫖒 +韻 韵 +響 响 +頁 页 +頂 顶 +頃 顷 +項 项 +順 顺 +頇 顸 +須 须 +頊 顼 +頌 颂 +頍 𫠆 +頎 颀 +頏 颃 +預 预 +頑 顽 +頒 颁 +頓 顿 +頗 颇 +領 领 +頜 颌 +頡 颉 +頤 颐 +頦 颏 +頫 𫖯 +頭 头 +頮 颒 +頰 颊 +頲 颋 +頴 颕 +頵 𫖳 +頷 颔 +頸 颈 +頹 颓 +頻 频 +頽 颓 +顂 𩓋 +顃 𩖖 +顅 𫖶 +顆 颗 +題 题 +額 额 +顎 颚 +顏 颜 +顒 颙 +顓 颛 +顔 颜 +顗 𫖮 +願 愿 𫖸 +顙 颡 +顛 颠 +類 类 +顢 颟 +顣 𫖹 +顥 颢 +顧 顾 +顫 颤 +顬 颥 +顯 显 +顰 颦 +顱 颅 +顳 颞 +顴 颧 +風 风 +颭 飐 +颮 飑 +颯 飒 +颰 𩙥 +颱 台 +颳 刮 +颶 飓 +颷 𩙪 +颸 飔 +颺 飏 +颻 飖 +颼 飕 +颾 𩙫 +飀 飗 +飄 飘 +飆 飙 +飈 飚 +飋 𫗋 +飛 飞 +飠 饣 +飢 饥 +飣 饤 +飥 饦 +飦 𫗞 +飩 饨 +飪 饪 +飫 饫 +飭 饬 +飯 饭 +飱 飧 +飲 饮 +飴 饴 +飵 𫗢 +飶 𫗣 +飼 饲 +飽 饱 +飾 饰 +飿 饳 +餃 饺 +餄 饸 +餅 饼 +餉 饷 +養 养 +餌 饵 +餎 饹 +餏 饻 +餑 饽 +餒 馁 +餓 饿 +餔 𫗦 +餕 馂 +餖 饾 +餗 𫗧 +餘 余 馀 +餚 肴 +餛 馄 +餜 馃 +餞 饯 +餡 馅 +餦 𫗠 +餧 𫗪 +館 馆 +餪 𫗬 +餫 𫗥 +餬 糊 𫗫 +餭 𫗮 +餱 糇 𫗯 +餳 饧 +餵 喂 𫗭 +餶 馉 +餷 馇 +餸 𩠌 +餺 馎 +餼 饩 +餾 馏 +餿 馊 +饁 馌 +饃 馍 +饅 馒 +饈 馐 +饉 馑 +饊 馓 +饋 馈 +饌 馔 +饑 饥 +饒 饶 +饗 飨 +饘 𫗴 +饜 餍 +饞 馋 +饟 𫗵 +饠 𫗩 +饢 馕 +馬 马 +馭 驭 +馮 冯 +馯 𫘛 +馱 驮 +馳 驰 +馴 驯 +馹 驲 +馼 𫘜 +駁 驳 +駃 𫘝 +駊 𫘟 +駎 𩧨 +駐 驻 +駑 驽 +駒 驹 +駔 驵 +駕 驾 +駘 骀 +駙 驸 +駚 𩧫 +駛 驶 +駝 驼 +駞 𫘞 +駟 驷 +駡 骂 +駢 骈 +駤 𫘠 +駧 𩧲 +駩 𩧴 +駫 𫘡 +駭 骇 +駰 骃 +駱 骆 +駶 𩧺 +駸 骎 +駻 𫘣 +駿 骏 +騁 骋 +騂 骍 +騃 𫘤 +騄 𫘧 +騅 骓 +騉 𫘥 +騊 𫘦 +騌 骔 +騍 骒 +騎 骑 +騏 骐 +騔 𩨀 +騖 骛 +騙 骗 +騚 𩨊 +騜 𫘩 +騝 𩨃 +騟 𩨈 +騠 𫘨 +騤 骙 +騧 䯄 +騪 𩨄 +騫 骞 +騭 骘 +騮 骝 +騰 腾 +騱 𫘬 +騴 𫘫 +騵 𫘪 +騶 驺 +騷 骚 +騸 骟 +騻 𫘭 +騼 𫠋 +騾 骡 +驀 蓦 +驁 骜 +驂 骖 +驃 骠 +驄 骢 𩨂 +驅 驱 +驊 骅 +驋 𩧯 +驌 骕 +驍 骁 +驏 骣 +驓 𫘯 +驕 骄 +驗 验 +驙 𫘰 +驚 惊 +驛 驿 +驟 骤 +驢 驴 +驤 骧 +驥 骥 +驦 骦 +驨 𫘱 +驪 骊 +驫 骉 +骯 肮 +髏 髅 +髒 脏 +體 体 +髕 髌 +髖 髋 +髮 发 +鬆 松 +鬍 胡 +鬖 𩭹 +鬚 须 +鬠 𫘽 +鬢 鬓 +鬥 斗 +鬧 闹 +鬨 哄 +鬩 阋 +鬮 阄 +鬱 郁 +鬹 鬶 +魎 魉 +魘 魇 +魚 鱼 +魛 鱽 +魟 𫚉 +魢 鱾 +魥 𩽹 +魦 𫚌 +魨 鲀 +魯 鲁 +魴 鲂 +魵 𫚍 +魷 鱿 +魺 鲄 +魽 𫠐 +鮁 鲅 +鮃 鲆 +鮄 𫚒 +鮅 𫚑 +鮆 𫚖 +鮊 鲌 +鮋 鲉 +鮍 鲏 +鮎 鲇 +鮐 鲐 +鮑 鲍 +鮒 鲋 +鮓 鲊 +鮕 𩾀 +鮚 鲒 +鮜 鲘 +鮝 鲞 +鮞 鲕 +鮟 𩽾 +鮣 䲟 +鮤 𫚓 +鮦 鲖 +鮪 鲔 +鮫 鲛 +鮭 鲑 +鮮 鲜 +鮯 𫚗 +鮰 𫚔 +鮳 鲓 +鮵 𫚛 +鮶 鲪 +鮸 𩾃 +鮺 鲝 +鮿 𫚚 +鯀 鲧 +鯁 鲠 +鯄 𩾁 +鯆 𫚙 +鯇 鲩 +鯉 鲤 +鯊 鲨 +鯒 鲬 +鯔 鲻 +鯕 鲯 +鯖 鲭 +鯗 鲞 +鯛 鲷 +鯝 鲴 +鯞 𫚡 +鯡 鲱 +鯢 鲵 +鯤 鲲 +鯧 鲳 +鯨 鲸 +鯪 鲮 +鯫 鲰 +鯬 𫚞 +鯰 鲶 +鯱 𩾇 +鯴 鲺 +鯶 𩽼 +鯷 鳀 +鯽 鲫 +鯾 𫚣 +鯿 鳊 +鰁 鳈 +鰂 鲗 +鰃 鳂 +鰆 䲠 +鰈 鲽 +鰉 鳇 +鰋 𫚢 +鰌 䲡 +鰍 鳅 +鰏 鲾 +鰐 鳄 +鰑 𫚊 +鰒 鳆 +鰓 鳃 +鰕 𫚥 +鰛 鳁 +鰜 鳒 +鰟 鳑 +鰠 鳋 +鰣 鲥 +鰤 𫚕 +鰥 鳏 +鰦 𫚤 +鰧 䲢 +鰨 鳎 +鰩 鳐 +鰫 𫚦 +鰭 鳍 +鰮 鳁 +鰱 鲢 +鰲 鳌 +鰳 鳓 +鰵 鳘 +鰷 鲦 +鰹 鲣 +鰺 鲹 +鰻 鳗 +鰼 鳛 +鰽 𫚧 +鰾 鳔 +鱂 鳉 +鱄 𫚋 +鱅 鳙 +鱆 𫠒 +鱇 𩾌 +鱈 鳕 +鱉 鳖 +鱊 𫚪 +鱒 鳟 +鱔 鳝 +鱖 鳜 +鱗 鳞 +鱘 鲟 +鱝 鲼 +鱟 鲎 +鱠 鲙 +鱢 𫚫 +鱣 鳣 +鱤 鳡 +鱧 鳢 +鱨 鲿 +鱭 鲚 +鱮 𫚈 +鱯 鳠 +鱲 𫚭 +鱷 鳄 +鱸 鲈 +鱺 鲡 +鳥 鸟 +鳧 凫 +鳩 鸠 +鳬 凫 +鳲 鸤 +鳳 凤 +鳴 鸣 +鳶 鸢 +鳷 𫛛 +鳼 𪉃 +鳽 𫛚 +鳾 䴓 +鴀 𫛜 +鴃 𫛞 +鴅 𫛝 +鴆 鸩 +鴇 鸨 +鴉 鸦 +鴐 𫛤 +鴒 鸰 +鴔 𫛡 +鴕 鸵 +鴗 𫁡 +鴛 鸳 +鴜 𪉈 +鴝 鸲 +鴞 鸮 +鴟 鸱 +鴣 鸪 +鴥 𫛣 +鴦 鸯 +鴨 鸭 +鴮 𫛦 +鴯 鸸 +鴰 鸹 +鴲 𪉆 +鴳 𫛩 +鴴 鸻 +鴷 䴕 +鴻 鸿 +鴽 𫛪 +鴿 鸽 +鵁 䴔 +鵂 鸺 +鵃 鸼 +鵊 𫛥 +鵐 鹀 +鵑 鹃 +鵒 鹆 +鵓 鹁 +鵚 𪉍 +鵜 鹈 +鵝 鹅 +鵟 𫛭 +鵠 鹄 +鵡 鹉 +鵧 𫛨 +鵩 𫛳 +鵪 鹌 +鵫 𫛱 +鵬 鹏 +鵮 鹐 +鵯 鹎 +鵰 雕 𫛲 +鵲 鹊 +鵷 鹓 +鵾 鹍 +鶄 䴖 +鶇 鸫 +鶉 鹑 +鶊 鹒 +鶌 𫛵 +鶒 𫛶 +鶓 鹋 +鶖 鹙 +鶗 𫛸 +鶘 鹕 +鶚 鹗 +鶡 鹖 +鶥 鹛 +鶦 𫛷 +鶩 鹜 +鶪 䴗 +鶬 鸧 +鶭 𫛯 +鶯 莺 +鶰 𫛫 +鶲 鹟 +鶴 鹤 +鶹 鹠 +鶺 鹡 +鶻 鹘 +鶼 鹣 +鶿 鹚 +鷀 鹚 +鷁 鹢 +鷂 鹞 +鷄 鸡 +鷅 𫛽 +鷈 䴘 +鷉 䴘 +鷊 鹝 +鷐 𫜀 +鷓 鹧 +鷔 𪉑 +鷖 鹥 +鷗 鸥 +鷙 鸷 +鷚 鹨 +鷣 𫜃 +鷤 𫛴 +鷥 鸶 +鷦 鹪 +鷨 𪉊 +鷩 𫜁 +鷫 鹔 +鷯 鹩 +鷲 鹫 +鷳 鹇 +鷴 鹇 +鷷 𫜄 +鷸 鹬 +鷹 鹰 +鷺 鹭 +鷽 鸴 +鷿 䴙 +鸂 㶉 +鸇 鹯 +鸊 䴙 +鸋 𫛢 +鸌 鹱 +鸏 鹲 +鸕 鸬 +鸗 𫛟 +鸘 鹴 +鸚 鹦 +鸛 鹳 +鸝 鹂 +鸞 鸾 +鹵 卤 +鹹 咸 +鹺 鹾 +鹼 碱 +鹽 盐 +麗 丽 +麥 麦 +麨 𪎊 +麩 麸 +麪 面 麺 +麫 面 +麬 𤿲 +麯 曲 +麲 𪎉 +麳 𪎌 +麴 曲 麹 +麵 面 麺 +麷 𫜑 +麼 么 麽 +麽 么 麽 +黃 黄 +黌 黉 +點 点 +黨 党 +黲 黪 +黴 霉 +黶 黡 +黷 黩 +黽 黾 +黿 鼋 +鼂 鼌 +鼉 鼍 +鼕 冬 +鼴 鼹 +齇 齄 +齊 齐 +齋 斋 +齎 赍 +齏 齑 +齒 齿 +齔 龀 +齕 龁 +齗 龂 +齙 龅 +齜 龇 +齟 龃 +齠 龆 +齡 龄 +齣 出 +齦 龈 +齧 啮 𫜩 +齩 𫜪 +齪 龊 +齬 龉 +齭 𫜭 +齯 𫠜 +齰 𫜬 +齲 龋 +齴 𫜮 +齶 腭 +齷 龌 +齾 𫜰 +龍 龙 +龎 厐 +龐 庞 +龑 䶮 +龓 𫜲 +龔 龚 +龕 龛 +龜 龟 +龭 𩨎 +龯 𨱆 +鿁 䜤 +𠁞 𠀾 +𠌥 𠆿 +𠏢 𠉗 +𠐊 𫝋 +𠗣 㓆 +𠞆 𠛆 +𠠎 𠚳 +𠬙 𪠡 +𠽃 𪠺 +𠿕 𪜎 +𡂡 𪢒 +𡃄 𪡺 +𡃕 𠴛 +𡃤 𪢐 +𡄔 𠴢 +𡄣 𠵸 +𡅏 𠲥 +𡅯 𪢖 +𡑭 𡋗 +𡓁 𪤄 +𡓾 𡋀 +𡔖 𡍣 +𡞵 㛟 +𡟫 𫝪 +𡠹 㛿 +𡡎 𡞱 +𡢃 㛠 +𡮉 𡭜 +𡮣 𡭬 +𡳳 𡳃 +𡸗 𪨩 +𡹬 𪨹 +𡻕 岁 +𡽗 𡸃 +𡾱 㟜 +𡿖 𪩛 +𢍰 𪪴 +𢠼 𢙑 +𢣐 𪬚 +𢣚 𢘝 +𢣭 𢘞 +𢤩 𪫡 +𢤱 𢘙 +𢤿 𪬯 +𢯷 𪭝 +𢶒 𪭯 +𢶫 𢫞 +𢷬 𢭏 +𢷮 𢫊 +𢹿 𢬦 +𢺳 𪮳 +𣈶 暅 +𣋋 𣈣 +𣍐 𠊉 +𣙎 㭣 +𣜬 𪳗 +𣝕 𣘷 +𣞻 𣘓 +𣠩 𣞎 +𣠲 𣑶 +𣯩 𣯣 +𣯴 𣭤 +𣯶 毶 +𣽏 𪶮 +𣾷 㳢 +𣿉 𣶫 +𤁣 𣺽 +𤄷 𪶒 +𤅶 𣷷 +𤑳 𤎻 +𤑹 𪹀 +𤒎 𤊀 +𤒻 𪹹 +𤓌 𪹠 +𤓩 𤊰 +𤘀 𪺣 +𤛮 𤙯 +𤛱 𫞢 +𤜆 𪺪 +𤠮 𪺸 +𤢟 𤝢 +𤢻 𢢐 +𤩂 𫞧 +𤪺 㻘 +𤫩 㻏 +𤬅 𪼴 +𤳷 𪽝 +𤳸 𤳄 +𤷃 𪽭 +𤸫 𤶧 +𤺔 𪽴 +𥊝 𥅿 +𥌃 𥅘 +𥏝 𪿊 +𥕥 𥐰 +𥖅 𥐯 +𥖲 𪿞 +𥗇 𪿵 +𥜐 𫀓 +𥜰 𫀌 +𥞵 𥞦 +𥢢 䅪 +𥢶 𫞷 +𥢷 𫀮 +𥨐 𥧂 +𥪂 𥩺 +𥯤 𫁳 +𥴨 𫂖 +𥴼 𫁺 +𥵃 𥱔 +𥵊 𥭉 +𥶽 𫁱 +𥸠 𥮋 +𥻦 𫂿 +𥼽 𥹥 +𥽖 𥺇 +𥾯 𫄝 +𥿊 𦈈 +𦀖 𫄦 +𦂅 𦈒 +𦃄 𦈗 +𦃩 𫄯 +𦅇 𫄪 +𦅈 𫄵 +𦆲 𫟇 +𦒀 𫅥 +𦔖 𫅼 +𦘧 𡳒 +𦟼 𫆝 +𦠅 𫞅 +𦡝 𫆫 +𦢈 𣍨 +𦣎 𦟗 +𦧺 𫇘 +𦪙 䑽 +𦪽 𦨩 +𦱌 𫇪 +𦾟 𦶻 +𧎈 𧌥 +𧒯 𫊹 +𧔥 𧒭 +𧕟 𧉐 +𧜗 䘞 +𧜵 䙊 +𧝞 䘛 +𧞫 𫌋 +𧟀 𧝧 +𧡴 𫌫 +𧢄 𫌬 +𧦝 𫍞 +𧦧 𫍟 +𧩕 𫍭 +𧩙 䜥 +𧩼 𫍶 +𧫝 𫍺 +𧬤 𫍼 +𧭈 𫍾 +𧭹 𫍐 +𧳟 𧳕 +𧵳 䞌 +𧶔 𧹓 +𧶧 䞎 +𧷎 𪠀 +𧸘 𫎨 +𧹈 𪥠 +𧽯 𫎸 +𨂐 𫏌 +𨄣 𨀱 +𨅍 𨁴 +𨆪 𫏕 +𨇁 𧿈 +𨇞 𨅫 +𨇤 𫏨 +𨇰 𫏞 +𨇽 𫏑 +𨈊 𨂺 +𨈌 𨄄 +𨊰 䢀 +𨊸 䢁 +𨊻 𨐆 +𨋢 䢂 +𨌈 𫐍 +𨍰 𫐔 +𨎌 𫐋 +𨎮 𨐉 +𨏠 𨐇 +𨏥 𨐊 +𨞺 𫟫 +𨟊 𫟬 +𨢿 𨡙 +𨣈 𨡺 +𨣞 𨟳 +𨣧 𨠨 +𨤻 𨤰 +𨥛 𨱀 +𨥟 𫓫 +𨦫 䦀 +𨧜 䦁 +𨧰 𫟽 +𨧱 𨱊 +𨨛 𫓼 +𨨢 𫓿 +𨩰 𫟾 +𨪕 𫓮 +𨫒 𨱐 +𨬖 𫔏 +𨭖 𫔑 +𨭸 𫔐 +𨮂 𨱕 +𨮳 𫔒 +𨯅 䥿 +𨯟 𫔓 +𨰃 𫔉 +𨰋 𫓳 +𨰥 𫔕 +𨰲 𫔃 +𨲳 𫔖 +𨳑 𨸁 +𨳕 𨸀 +𨴗 𨸅 +𨴹 𫔲 +𨵩 𨸆 +𨵸 𨸇 +𨶀 𨸉 +𨶏 𨸊 +𨶮 𨸌 +𨶲 𨸋 +𨷲 𨸎 +𨼳 𫔽 +𨽏 𨸘 +𩀨 𫕚 +𩅙 𫕨 +𩎖 𫖑 +𩎢 𩏾 +𩏂 𫖓 +𩏠 𫖖 +𩏪 𩏽 +𩏷 𫃗 +𩑔 𫖪 +𩒎 𫖭 +𩓣 𩖕 +𩓥 𫖵 +𩔑 𫖷 +𩔳 𫖴 +𩖰 𫠇 +𩗀 𩙦 +𩗓 𫗈 +𩗴 𫗉 +𩘀 𩙩 +𩘝 𩙭 +𩘹 𩙨 +𩘺 𩙬 +𩙈 𩙰 +𩚛 𩟿 +𩚥 𩠀 +𩚩 𫗡 +𩚵 𩠁 +𩛆 𩠂 +𩛌 𫗤 +𩛡 𫗨 +𩛩 𩠃 +𩜇 𩠉 +𩜦 𩠆 +𩜵 𩠊 +𩝔 𩠋 +𩝽 𫗳 +𩞄 𩠎 +𩞦 𩠏 +𩞯 䭪 +𩟐 𩠅 +𩟗 𫗚 +𩠴 𩠠 +𩡣 𩡖 +𩡺 𩧦 +𩢡 𩧬 +𩢴 𩧵 +𩢸 𩧳 +𩢾 𩧮 +𩣏 𩧶 +𩣑 䯃 +𩣫 𩧸 +𩣵 𩧻 +𩣺 𩧼 +𩤊 𩧩 +𩤙 𩨆 +𩤲 𩨉 +𩤸 𩨅 +𩥄 𩨋 +𩥇 𩨍 +𩥉 𩧱 +𩥑 𩨌 +𩦠 𫠌 +𩧆 𩨐 +𩭙 𩬣 +𩯁 𫙂 +𩯳 𩯒 +𩰀 𩬤 +𩰹 𩰰 +𩳤 𩲒 +𩴵 𩴌 +𩵦 𫠏 +𩵩 𩽺 +𩵹 𩽻 +𩶁 𫚎 +𩶘 䲞 +𩶰 𩽿 +𩶱 𩽽 +𩷰 𩾄 +𩸃 𩾅 +𩸄 𫚝 +𩸡 𫚟 +𩸦 𩾆 +𩻗 𫚨 +𩻬 𫚩 +𩻮 𫚘 +𩼶 𫚬 +𩽇 𩾎 +𩿅 𫠖 +𩿤 𫛠 +𩿪 𪉄 +𪀖 𫛧 +𪀦 𪉅 +𪀾 𪉋 +𪁈 𪉉 +𪁖 𪉌 +𪂆 𪉎 +𪃍 𪉐 +𪃏 𪉏 +𪃒 𫛻 +𪃧 𫛹 +𪄆 𪉔 +𪄕 𪉒 +𪅂 𫜂 +𪆷 𫛾 +𪇳 𪉕 +𪈼 𪉓 +𪉸 𫜊 +𪋿 𪎍 +𪌭 𫜓 +𪍠 𫜕 +𪓰 𫜟 +𪔵 𪔭 +𪘀 𪚏 +𪘯 𪚐 +𪙏 𫜯 +𪟖 𠛾 +𪷓 𣶭 +𫒡 𫓷 +𫜦 𫜫 diff --git a/tools/mktable.go b/tools/mktable.go new file mode 100644 index 0000000..04ae9ab --- /dev/null +++ b/tools/mktable.go @@ -0,0 +1,62 @@ +// Copyright 2013 . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build ingore + +package main + +import ( + "bufio" + "bytes" + "fmt" + "io/ioutil" + "log" + "os" + "strings" + "unicode/utf8" +) + +func main() { + f, err := os.Open("./TSCharacters.txt") + if err != nil { + log.Fatal("open failed:", err) + } + defer f.Close() + + br := bufio.NewReader(f) + + var out bytes.Buffer + fmt.Fprintf(&out, ` +// Copyright 2013 . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Auto generated by go generate, DO NOT EDIT !!! + +package main + +var _TSCharactersMap = map[rune]rune{ +`[1:]) + for i := 0; i < 1<<20; i++ { + data, isPrefix, err := br.ReadLine() + if err != nil || isPrefix { + break + } + if !utf8.ValidString(string(data)) { + continue + } + + line := strings.Replace(string(data), "\t", " ", -1) + ss := strings.Split(string(line), " ") + + if len(ss) >= 2 { + tw := strings.TrimSpace(ss[0]) + zh := strings.TrimSpace(ss[1]) + fmt.Fprintf(&out, "\t'%s': '%s',\n", tw, zh) + } + } + fmt.Fprintf(&out, "}\n") + + ioutil.WriteFile("z_TSCharacters.go", []byte(out.Bytes()), 0666) +} diff --git a/trans-terms.md b/trans-terms.md new file mode 100644 index 0000000..2adebdd --- /dev/null +++ b/trans-terms.md @@ -0,0 +1,71 @@ +# 朮語翻譯 + +單詞 | 譯法 | 詞性 | 類彆 | 備註 +----------------- | ----------------- | ------ | ---- | ---- +approximation | 近似[值]/逼近式 | n | | +argument | 實參 | n | | +assignment | 賦值 | n | | +block | 塊/阻塞 | n | | “阻塞”僅用於信道 +body | 執行體 | n | | +buffer | 緩衝區 | n | | +cache | 緩存 | n | | +case | 情況/寫法 | n | | 在用作大小寫時譯作“寫法”,因為有些字母還有其它多種寫法 +channel | 信道 | n | | +char/character | 字符 | n | | +code point | 碼點 | n | | +coefficient | 繫數 | n | | +commit | 提交 | v | | 卽直接曏repo提交代碼 +compatibility | 兼容性 | n/adj | | +complex | 復數 | n | | +constant | 常量 | n | | +constructor | 構造函數 | n | | +convention | 約定 | n | | +defer | 推遲 | v | | +degree | 階 | n | | 僅用於多項式 +distribute | 分髮 | v | | +distribution | 分髮 | n | | +embedding | 內嵌 | n/v | | 用作類型,與“嵌入式”分開 +error | 錯誤/誤差 | n | | “誤差”用於數學 +evaluation | 求值 | n | | +even | 偶(數) | n/adj | | +expression | 錶達式 | n | | +flag | 標誌 | n | | +floating-point | 浮點數 | n | | +form | 形式 | n | | +function | 函數 | n | | +implementation | 實現 | n | | +integer | 整數 | n | | +introduction | 引言 | n | | +label | 標簽 | n/v | | +lock | 鎖 | n/v | | +method | 方法 | n | | +mutex | 互斥鎖 | n | | +name space | 命名空間 | n | | +normalize | 規範化 | v | | +odd | 奇(數) | n/adj | | +panic |(保留) | n/v | | +parameter | 形參 | n | | +pending | 待定/掛起 | adj | | +polynomial | 多項式 | n | | +profile/profiling | 評估 | n/v | | +race | 競爭/競態 | n/v | | +recover | 恢復 | v | | +reduction | 換算 | n | | +reference | 引用 | n/v | | +repository | [源碼]倉庫/源碼庫 | n | | +round | 捨入 | v/adj | | 在數學中為捨入 +rune | 符文 | n | | +scope | 作用域 | n | | +script | 腳本/書寫[繫統] | n | | 在Unicode中譯作“書寫[繫統]” +source code | 源碼/源代碼 | n | | +statement | 語句 | n | | +stride | 間距 | n | | 用作兩個碼點的間距。如從A(0x41)到a(0x61)的間距為32(0x20) +struct | 結構體 | n | | +submit | 遞交 | v | | 指遞交至主代碼樹 +tag | 標記 | n | | 多指struct tag,上下文隻與xml/html相關時仍作“標簽” +token | [詞法]標記 | n | | +ulp | 末尾單元 | n | | Unit in the Last Place 的縮寫 +universe block | 全域塊 | n | | +variable | 變量 | n | | + +說明: 如果對翻譯有更好的建議請 [創建ISSUE](https://github.com/golang-china/gopl-zh/issues/new) 參與討論。添加新詞請按字符串排序。 diff --git a/vendor/gopl.io/README.md b/vendor/gopl.io/README.md new file mode 100644 index 0000000..2be13ea --- /dev/null +++ b/vendor/gopl.io/README.md @@ -0,0 +1,21 @@ +# The Go Programming Language + +This repository provides the downloadable example programs +for the book, "The Go Programming Language"; see http://www.gopl.io. + +These example programs are licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
+Creative Commons License + +You can download, build, and run the programs with the following commands: + + $ export GOPATH=$HOME/gobook # choose workspace directory + $ go get gopl.io/ch1/helloworld # fetch, build, install + $ $GOPATH/bin/helloworld # run + Hello, 世界 + +Many of the programs contain comments of the form `//!+` and `//!-`. +These comments bracket the parts of the programs that are excerpted in the +book; you can safely ignore them. In a few cases, programs +have been reformatted in an unnatural way so that they can be presented +in stages in the book. + diff --git a/vendor/gopl.io/ch1/dup1/main.go b/vendor/gopl.io/ch1/dup1/main.go new file mode 100644 index 0000000..f476741 --- /dev/null +++ b/vendor/gopl.io/ch1/dup1/main.go @@ -0,0 +1,31 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 8. +//!+ + +// Dup1 prints the text of each line that appears more than +// once in the standard input, preceded by its count. +package main + +import ( + "bufio" + "fmt" + "os" +) + +func main() { + counts := make(map[string]int) + input := bufio.NewScanner(os.Stdin) + for input.Scan() { + counts[input.Text()]++ + } + // NOTE: ignoring potential errors from input.Err() + for line, n := range counts { + if n > 1 { + fmt.Printf("%d\t%s\n", n, line) + } + } +} + +//!- diff --git a/vendor/gopl.io/ch1/dup2/main.go b/vendor/gopl.io/ch1/dup2/main.go new file mode 100644 index 0000000..e894f84 --- /dev/null +++ b/vendor/gopl.io/ch1/dup2/main.go @@ -0,0 +1,48 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 10. +//!+ + +// Dup2 prints the count and text of lines that appear more than once +// in the input. It reads from stdin or from a list of named files. +package main + +import ( + "bufio" + "fmt" + "os" +) + +func main() { + counts := make(map[string]int) + files := os.Args[1:] + if len(files) == 0 { + countLines(os.Stdin, counts) + } else { + for _, arg := range files { + f, err := os.Open(arg) + if err != nil { + fmt.Fprintf(os.Stderr, "dup2: %v\n", err) + continue + } + countLines(f, counts) + f.Close() + } + } + for line, n := range counts { + if n > 1 { + fmt.Printf("%d\t%s\n", n, line) + } + } +} + +func countLines(f *os.File, counts map[string]int) { + input := bufio.NewScanner(f) + for input.Scan() { + counts[input.Text()]++ + } + // NOTE: ignoring potential errors from input.Err() +} + +//!- diff --git a/vendor/gopl.io/ch1/dup3/main.go b/vendor/gopl.io/ch1/dup3/main.go new file mode 100644 index 0000000..50434d8 --- /dev/null +++ b/vendor/gopl.io/ch1/dup3/main.go @@ -0,0 +1,38 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 12. + +//!+ + +// Dup3 prints the count and text of lines that +// appear more than once in the named input files. +package main + +import ( + "fmt" + "io/ioutil" + "os" + "strings" +) + +func main() { + counts := make(map[string]int) + for _, filename := range os.Args[1:] { + data, err := ioutil.ReadFile(filename) + if err != nil { + fmt.Fprintf(os.Stderr, "dup3: %v\n", err) + continue + } + for _, line := range strings.Split(string(data), "\n") { + counts[line]++ + } + } + for line, n := range counts { + if n > 1 { + fmt.Printf("%d\t%s\n", n, line) + } + } +} + +//!- diff --git a/vendor/gopl.io/ch1/echo1/main.go b/vendor/gopl.io/ch1/echo1/main.go new file mode 100644 index 0000000..e8f8969 --- /dev/null +++ b/vendor/gopl.io/ch1/echo1/main.go @@ -0,0 +1,24 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 4. +//!+ + +// Echo1 prints its command-line arguments. +package main + +import ( + "fmt" + "os" +) + +func main() { + var s, sep string + for i := 1; i < len(os.Args); i++ { + s += sep + os.Args[i] + sep = " " + } + fmt.Println(s) +} + +//!- diff --git a/vendor/gopl.io/ch1/echo2/main.go b/vendor/gopl.io/ch1/echo2/main.go new file mode 100644 index 0000000..82d312c --- /dev/null +++ b/vendor/gopl.io/ch1/echo2/main.go @@ -0,0 +1,24 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 6. +//!+ + +// Echo2 prints its command-line arguments. +package main + +import ( + "fmt" + "os" +) + +func main() { + s, sep := "", "" + for _, arg := range os.Args[1:] { + s += sep + arg + sep = " " + } + fmt.Println(s) +} + +//!- diff --git a/vendor/gopl.io/ch1/echo3/main.go b/vendor/gopl.io/ch1/echo3/main.go new file mode 100644 index 0000000..031a650 --- /dev/null +++ b/vendor/gopl.io/ch1/echo3/main.go @@ -0,0 +1,20 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 8. + +// Echo3 prints its command-line arguments. +package main + +import ( + "fmt" + "os" + "strings" +) + +//!+ +func main() { + fmt.Println(strings.Join(os.Args[1:], " ")) +} + +//!- diff --git a/vendor/gopl.io/ch1/fetch/main.go b/vendor/gopl.io/ch1/fetch/main.go new file mode 100644 index 0000000..e704ae6 --- /dev/null +++ b/vendor/gopl.io/ch1/fetch/main.go @@ -0,0 +1,34 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 16. +//!+ + +// Fetch prints the content found at each specified URL. +package main + +import ( + "fmt" + "io/ioutil" + "net/http" + "os" +) + +func main() { + for _, url := range os.Args[1:] { + resp, err := http.Get(url) + if err != nil { + fmt.Fprintf(os.Stderr, "fetch: %v\n", err) + os.Exit(1) + } + b, err := ioutil.ReadAll(resp.Body) + resp.Body.Close() + if err != nil { + fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err) + os.Exit(1) + } + fmt.Printf("%s", b) + } +} + +//!- diff --git a/vendor/gopl.io/ch1/fetchall/main.go b/vendor/gopl.io/ch1/fetchall/main.go new file mode 100644 index 0000000..ad32109 --- /dev/null +++ b/vendor/gopl.io/ch1/fetchall/main.go @@ -0,0 +1,49 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 17. +//!+ + +// Fetchall fetches URLs in parallel and reports their times and sizes. +package main + +import ( + "fmt" + "io" + "io/ioutil" + "net/http" + "os" + "time" +) + +func main() { + start := time.Now() + ch := make(chan string) + for _, url := range os.Args[1:] { + go fetch(url, ch) // start a goroutine + } + for range os.Args[1:] { + fmt.Println(<-ch) // receive from channel ch + } + fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds()) +} + +func fetch(url string, ch chan<- string) { + start := time.Now() + resp, err := http.Get(url) + if err != nil { + ch <- fmt.Sprint(err) // send to channel ch + return + } + + nbytes, err := io.Copy(ioutil.Discard, resp.Body) + resp.Body.Close() // don't leak resources + if err != nil { + ch <- fmt.Sprintf("while reading %s: %v", url, err) + return + } + secs := time.Since(start).Seconds() + ch <- fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url) +} + +//!- diff --git a/vendor/gopl.io/ch1/helloworld/main.go b/vendor/gopl.io/ch1/helloworld/main.go new file mode 100644 index 0000000..cd5e0ab --- /dev/null +++ b/vendor/gopl.io/ch1/helloworld/main.go @@ -0,0 +1,16 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 1. + +// Helloworld is our first Go program. +//!+ +package main + +import "fmt" + +func main() { + fmt.Println("Hello, 世界") +} + +//!- diff --git a/vendor/gopl.io/ch1/lissajous/main.go b/vendor/gopl.io/ch1/lissajous/main.go new file mode 100644 index 0000000..be50e70 --- /dev/null +++ b/vendor/gopl.io/ch1/lissajous/main.go @@ -0,0 +1,86 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// Run with "web" command-line argument for web server. +// See page 13. +//!+main + +// Lissajous generates GIF animations of random Lissajous figures. +package main + +import ( + "image" + "image/color" + "image/gif" + "io" + "math" + "math/rand" + "os" +) + +//!-main +// Packages not needed by version in book. +import ( + "log" + "net/http" + "time" +) + +//!+main + +var palette = []color.Color{color.White, color.Black} + +const ( + whiteIndex = 0 // first color in palette + blackIndex = 1 // next color in palette +) + +func main() { + //!-main + // The sequence of images is deterministic unless we seed + // the pseudo-random number generator using the current time. + // Thanks to Randall McPherson for pointing out the omission. + rand.Seed(time.Now().UTC().UnixNano()) + + if len(os.Args) > 1 && os.Args[1] == "web" { + //!+http + handler := func(w http.ResponseWriter, r *http.Request) { + lissajous(w) + } + http.HandleFunc("/", handler) + //!-http + log.Fatal(http.ListenAndServe("localhost:8000", nil)) + return + } + //!+main + lissajous(os.Stdout) +} + +func lissajous(out io.Writer) { + const ( + cycles = 5 // number of complete x oscillator revolutions + res = 0.001 // angular resolution + size = 100 // image canvas covers [-size..+size] + nframes = 64 // number of animation frames + delay = 8 // delay between frames in 10ms units + ) + freq := rand.Float64() * 3.0 // relative frequency of y oscillator + anim := gif.GIF{LoopCount: nframes} + phase := 0.0 // phase difference + for i := 0; i < nframes; i++ { + rect := image.Rect(0, 0, 2*size+1, 2*size+1) + img := image.NewPaletted(rect, palette) + for t := 0.0; t < cycles*2*math.Pi; t += res { + x := math.Sin(t) + y := math.Sin(t*freq + phase) + img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5), + blackIndex) + } + phase += 0.1 + anim.Delay = append(anim.Delay, delay) + anim.Image = append(anim.Image, img) + } + gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors +} + +//!-main diff --git a/vendor/gopl.io/ch1/server1/main.go b/vendor/gopl.io/ch1/server1/main.go new file mode 100644 index 0000000..600e92c --- /dev/null +++ b/vendor/gopl.io/ch1/server1/main.go @@ -0,0 +1,26 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 19. +//!+ + +// Server1 is a minimal "echo" server. +package main + +import ( + "fmt" + "log" + "net/http" +) + +func main() { + http.HandleFunc("/", handler) // each request calls handler + log.Fatal(http.ListenAndServe("localhost:8000", nil)) +} + +// handler echoes the Path component of the requested URL. +func handler(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path) +} + +//!- diff --git a/vendor/gopl.io/ch1/server2/main.go b/vendor/gopl.io/ch1/server2/main.go new file mode 100644 index 0000000..dd8ec57 --- /dev/null +++ b/vendor/gopl.io/ch1/server2/main.go @@ -0,0 +1,41 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 20. +//!+ + +// Server2 is a minimal "echo" and counter server. +package main + +import ( + "fmt" + "log" + "net/http" + "sync" +) + +var mu sync.Mutex +var count int + +func main() { + http.HandleFunc("/", handler) + http.HandleFunc("/count", counter) + log.Fatal(http.ListenAndServe("localhost:8000", nil)) +} + +// handler echoes the Path component of the requested URL. +func handler(w http.ResponseWriter, r *http.Request) { + mu.Lock() + count++ + mu.Unlock() + fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path) +} + +// counter echoes the number of calls so far. +func counter(w http.ResponseWriter, r *http.Request) { + mu.Lock() + fmt.Fprintf(w, "Count %d\n", count) + mu.Unlock() +} + +//!- diff --git a/vendor/gopl.io/ch1/server3/main.go b/vendor/gopl.io/ch1/server3/main.go new file mode 100644 index 0000000..88c4ad5 --- /dev/null +++ b/vendor/gopl.io/ch1/server3/main.go @@ -0,0 +1,37 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 21. + +// Server3 is an "echo" server that displays request parameters. +package main + +import ( + "fmt" + "log" + "net/http" +) + +func main() { + http.HandleFunc("/", handler) + log.Fatal(http.ListenAndServe("localhost:8000", nil)) +} + +//!+handler +// handler echoes the HTTP request. +func handler(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto) + for k, v := range r.Header { + fmt.Fprintf(w, "Header[%q] = %q\n", k, v) + } + fmt.Fprintf(w, "Host = %q\n", r.Host) + fmt.Fprintf(w, "RemoteAddr = %q\n", r.RemoteAddr) + if err := r.ParseForm(); err != nil { + log.Print(err) + } + for k, v := range r.Form { + fmt.Fprintf(w, "Form[%q] = %q\n", k, v) + } +} + +//!-handler diff --git a/vendor/gopl.io/ch10/cross/main.go b/vendor/gopl.io/ch10/cross/main.go new file mode 100644 index 0000000..1de5cf5 --- /dev/null +++ b/vendor/gopl.io/ch10/cross/main.go @@ -0,0 +1,19 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 295. + +// The cross command prints the values of GOOS and GOARCH for this target. +package main + +import ( + "fmt" + "runtime" +) + +//!+ +func main() { + fmt.Println(runtime.GOOS, runtime.GOARCH) +} + +//!- diff --git a/vendor/gopl.io/ch10/jpeg/main.go b/vendor/gopl.io/ch10/jpeg/main.go new file mode 100644 index 0000000..ca84efb --- /dev/null +++ b/vendor/gopl.io/ch10/jpeg/main.go @@ -0,0 +1,52 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 287. + +//!+main + +// The jpeg command reads a PNG image from the standard input +// and writes it as a JPEG image to the standard output. +package main + +import ( + "fmt" + "image" + "image/jpeg" + _ "image/png" // register PNG decoder + "io" + "os" +) + +func main() { + if err := toJPEG(os.Stdin, os.Stdout); err != nil { + fmt.Fprintf(os.Stderr, "jpeg: %v\n", err) + os.Exit(1) + } +} + +func toJPEG(in io.Reader, out io.Writer) error { + img, kind, err := image.Decode(in) + if err != nil { + return err + } + fmt.Fprintln(os.Stderr, "Input format =", kind) + return jpeg.Encode(out, img, &jpeg.Options{Quality: 95}) +} + +//!-main + +/* +//!+with +$ go build gopl.io/ch3/mandelbrot +$ go build gopl.io/ch10/jpeg +$ ./mandelbrot | ./jpeg >mandelbrot.jpg +Input format = png +//!-with + +//!+without +$ go build gopl.io/ch10/jpeg +$ ./mandelbrot | ./jpeg >mandelbrot.jpg +jpeg: image: unknown format +//!-without +*/ diff --git a/vendor/gopl.io/ch11/echo/echo.go b/vendor/gopl.io/ch11/echo/echo.go new file mode 100644 index 0000000..82b5a3e --- /dev/null +++ b/vendor/gopl.io/ch11/echo/echo.go @@ -0,0 +1,41 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 308. +//!+ + +// Echo prints its command-line arguments. +package main + +import ( + "flag" + "fmt" + "io" + "os" + "strings" +) + +var ( + n = flag.Bool("n", false, "omit trailing newline") + s = flag.String("s", " ", "separator") +) + +var out io.Writer = os.Stdout // modified during testing + +func main() { + flag.Parse() + if err := echo(!*n, *s, flag.Args()); err != nil { + fmt.Fprintf(os.Stderr, "echo: %v\n", err) + os.Exit(1) + } +} + +func echo(newline bool, sep string, args []string) error { + fmt.Fprint(out, strings.Join(args, sep)) + if newline { + fmt.Fprintln(out) + } + return nil +} + +//!- diff --git a/vendor/gopl.io/ch11/echo/echo_test.go b/vendor/gopl.io/ch11/echo/echo_test.go new file mode 100644 index 0000000..7d2f47a --- /dev/null +++ b/vendor/gopl.io/ch11/echo/echo_test.go @@ -0,0 +1,45 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// Test of echo command. Run with: go test gopl.io/ch11/echo + +//!+ +package main + +import ( + "bytes" + "fmt" + "testing" +) + +func TestEcho(t *testing.T) { + var tests = []struct { + newline bool + sep string + args []string + want string + }{ + {true, "", []string{}, "\n"}, + {false, "", []string{}, ""}, + {true, "\t", []string{"one", "two", "three"}, "one\ttwo\tthree\n"}, + {true, ",", []string{"a", "b", "c"}, "a,b,c\n"}, + {false, ":", []string{"1", "2", "3"}, "1:2:3"}, + } + + for _, test := range tests { + descr := fmt.Sprintf("echo(%v, %q, %q)", + test.newline, test.sep, test.args) + + out = new(bytes.Buffer) // captured output + if err := echo(test.newline, test.sep, test.args); err != nil { + t.Errorf("%s failed: %v", descr, err) + continue + } + got := out.(*bytes.Buffer).String() + if got != test.want { + t.Errorf("%s = %q, want %q", descr, got, test.want) + } + } +} + +//!- diff --git a/vendor/gopl.io/ch11/storage1/storage.go b/vendor/gopl.io/ch11/storage1/storage.go new file mode 100644 index 0000000..ed8982c --- /dev/null +++ b/vendor/gopl.io/ch11/storage1/storage.go @@ -0,0 +1,45 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 311. + +// Package storage is part of a hypothetical cloud storage server. +//!+main +package storage + +import ( + "fmt" + "log" + "net/smtp" +) + +var usage = make(map[string]int64) + +func bytesInUse(username string) int64 { return usage[username] } + +// Email sender configuration. +// NOTE: never put passwords in source code! +const sender = "notifications@example.com" +const password = "correcthorsebatterystaple" +const hostname = "smtp.example.com" + +const template = `Warning: you are using %d bytes of storage, +%d%% of your quota.` + +func CheckQuota(username string) { + used := bytesInUse(username) + const quota = 1000000000 // 1GB + percent := 100 * used / quota + if percent < 90 { + return // OK + } + msg := fmt.Sprintf(template, used, percent) + auth := smtp.PlainAuth("", sender, password, hostname) + err := smtp.SendMail(hostname+":587", auth, sender, + []string{username}, []byte(msg)) + if err != nil { + log.Printf("smtp.SendMail(%s) failed: %s", username, err) + } +} + +//!-main diff --git a/vendor/gopl.io/ch11/storage2/quota_test.go b/vendor/gopl.io/ch11/storage2/quota_test.go new file mode 100644 index 0000000..2dcd045 --- /dev/null +++ b/vendor/gopl.io/ch11/storage2/quota_test.go @@ -0,0 +1,53 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +//!+test +package storage + +import ( + "strings" + "testing" +) + +func TestCheckQuotaNotifiesUser(t *testing.T) { + var notifiedUser, notifiedMsg string + notifyUser = func(user, msg string) { + notifiedUser, notifiedMsg = user, msg + } + + const user = "joe@example.org" + usage[user] = 980000000 // simulate a 980MB-used condition + + CheckQuota(user) + if notifiedUser == "" && notifiedMsg == "" { + t.Fatalf("notifyUser not called") + } + if notifiedUser != user { + t.Errorf("wrong user (%s) notified, want %s", + notifiedUser, user) + } + const wantSubstring = "98% of your quota" + if !strings.Contains(notifiedMsg, wantSubstring) { + t.Errorf("unexpected notification message <<%s>>, "+ + "want substring %q", notifiedMsg, wantSubstring) + } +} + +//!-test + +/* +//!+defer +func TestCheckQuotaNotifiesUser(t *testing.T) { + // Save and restore original notifyUser. + saved := notifyUser + defer func() { notifyUser = saved }() + + // Install the test's fake notifyUser. + var notifiedUser, notifiedMsg string + notifyUser = func(user, msg string) { + notifiedUser, notifiedMsg = user, msg + } + // ...rest of test... +} +//!-defer +*/ diff --git a/vendor/gopl.io/ch11/storage2/storage.go b/vendor/gopl.io/ch11/storage2/storage.go new file mode 100644 index 0000000..f103fbb --- /dev/null +++ b/vendor/gopl.io/ch11/storage2/storage.go @@ -0,0 +1,49 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 312. + +// Package storage is part of a hypothetical cloud storage server. +package storage + +import ( + "fmt" + "log" + "net/smtp" +) + +var usage = make(map[string]int64) + +func bytesInUse(username string) int64 { return usage[username] } + +// E-mail sender configuration. +// NOTE: never put passwords in source code! +const sender = "notifications@example.com" +const password = "correcthorsebatterystaple" +const hostname = "smtp.example.com" + +const template = `Warning: you are using %d bytes of storage, +%d%% of your quota.` + +//!+factored +var notifyUser = func(username, msg string) { + auth := smtp.PlainAuth("", sender, password, hostname) + err := smtp.SendMail(hostname+":587", auth, sender, + []string{username}, []byte(msg)) + if err != nil { + log.Printf("smtp.SendEmail(%s) failed: %s", username, err) + } +} + +func CheckQuota(username string) { + used := bytesInUse(username) + const quota = 1000000000 // 1GB + percent := 100 * used / quota + if percent < 90 { + return // OK + } + msg := fmt.Sprintf(template, used, percent) + notifyUser(username, msg) +} + +//!-factored diff --git a/vendor/gopl.io/ch11/word1/word.go b/vendor/gopl.io/ch11/word1/word.go new file mode 100644 index 0000000..048abc9 --- /dev/null +++ b/vendor/gopl.io/ch11/word1/word.go @@ -0,0 +1,21 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 303. +//!+ + +// Package word provides utilities for word games. +package word + +// IsPalindrome reports whether s reads the same forward and backward. +// (Our first attempt.) +func IsPalindrome(s string) bool { + for i := range s { + if s[i] != s[len(s)-1-i] { + return false + } + } + return true +} + +//!- diff --git a/vendor/gopl.io/ch11/word1/word_test.go b/vendor/gopl.io/ch11/word1/word_test.go new file mode 100644 index 0000000..bb53404 --- /dev/null +++ b/vendor/gopl.io/ch11/word1/word_test.go @@ -0,0 +1,43 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +//!+test +package word + +import "testing" + +func TestPalindrome(t *testing.T) { + if !IsPalindrome("detartrated") { + t.Error(`IsPalindrome("detartrated") = false`) + } + if !IsPalindrome("kayak") { + t.Error(`IsPalindrome("kayak") = false`) + } +} + +func TestNonPalindrome(t *testing.T) { + if IsPalindrome("palindrome") { + t.Error(`IsPalindrome("palindrome") = true`) + } +} + +//!-test + +// The tests below are expected to fail. +// See package gopl.io/ch11/word2 for the fix. + +//!+more +func TestFrenchPalindrome(t *testing.T) { + if !IsPalindrome("été") { + t.Error(`IsPalindrome("été") = false`) + } +} + +func TestCanalPalindrome(t *testing.T) { + input := "A man, a plan, a canal: Panama" + if !IsPalindrome(input) { + t.Errorf(`IsPalindrome(%q) = false`, input) + } +} + +//!-more diff --git a/vendor/gopl.io/ch11/word2/word.go b/vendor/gopl.io/ch11/word2/word.go new file mode 100644 index 0000000..846c8d2 --- /dev/null +++ b/vendor/gopl.io/ch11/word2/word.go @@ -0,0 +1,29 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 305. +//!+ + +// Package word provides utilities for word games. +package word + +import "unicode" + +// IsPalindrome reports whether s reads the same forward and backward. +// Letter case is ignored, as are non-letters. +func IsPalindrome(s string) bool { + var letters []rune + for _, r := range s { + if unicode.IsLetter(r) { + letters = append(letters, unicode.ToLower(r)) + } + } + for i := range letters { + if letters[i] != letters[len(letters)-1-i] { + return false + } + } + return true +} + +//!- diff --git a/vendor/gopl.io/ch11/word2/word_test.go b/vendor/gopl.io/ch11/word2/word_test.go new file mode 100644 index 0000000..4b17337 --- /dev/null +++ b/vendor/gopl.io/ch11/word2/word_test.go @@ -0,0 +1,148 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package word + +import ( + "fmt" + "math/rand" + "time" +) + +//!+bench + +import "testing" + +//!-bench + +//!+test +func TestIsPalindrome(t *testing.T) { + var tests = []struct { + input string + want bool + }{ + {"", true}, + {"a", true}, + {"aa", true}, + {"ab", false}, + {"kayak", true}, + {"detartrated", true}, + {"A man, a plan, a canal: Panama", true}, + {"Evil I did dwell; lewd did I live.", true}, + {"Able was I ere I saw Elba", true}, + {"été", true}, + {"Et se resservir, ivresse reste.", true}, + {"palindrome", false}, // non-palindrome + {"desserts", false}, // semi-palindrome + } + for _, test := range tests { + if got := IsPalindrome(test.input); got != test.want { + t.Errorf("IsPalindrome(%q) = %v", test.input, got) + } + } +} + +//!-test + +//!+bench +func BenchmarkIsPalindrome(b *testing.B) { + for i := 0; i < b.N; i++ { + IsPalindrome("A man, a plan, a canal: Panama") + } +} + +//!-bench + +//!+example + +func ExampleIsPalindrome() { + fmt.Println(IsPalindrome("A man, a plan, a canal: Panama")) + fmt.Println(IsPalindrome("palindrome")) + // Output: + // true + // false +} + +//!-example + +/* +//!+random +import "math/rand" + +//!-random +*/ + +//!+random +// randomPalindrome returns a palindrome whose length and contents +// are derived from the pseudo-random number generator rng. +func randomPalindrome(rng *rand.Rand) string { + n := rng.Intn(25) // random length up to 24 + runes := make([]rune, n) + for i := 0; i < (n+1)/2; i++ { + r := rune(rng.Intn(0x1000)) // random rune up to '\u0999' + runes[i] = r + runes[n-1-i] = r + } + return string(runes) +} + +func TestRandomPalindromes(t *testing.T) { + // Initialize a pseudo-random number generator. + seed := time.Now().UTC().UnixNano() + t.Logf("Random seed: %d", seed) + rng := rand.New(rand.NewSource(seed)) + + for i := 0; i < 1000; i++ { + p := randomPalindrome(rng) + if !IsPalindrome(p) { + t.Errorf("IsPalindrome(%q) = false", p) + } + } +} + +//!-random + +/* +// Answer for Exercicse 11.1: Modify randomPalindrome to exercise +// IsPalindrome's handling of punctuation and spaces. + +// WARNING: the conversion r -> upper -> lower doesn't preserve +// the value of r in some cases, e.g., µ Μ, ſ S, ı I + +// randomPalindrome returns a palindrome whose length and contents +// are derived from the pseudo-random number generator rng. +func randomNoisyPalindrome(rng *rand.Rand) string { + n := rng.Intn(25) // random length up to 24 + runes := make([]rune, n) + for i := 0; i < (n+1)/2; i++ { + r := rune(rng.Intn(0x200)) // random rune up to \u99 + runes[i] = r + r1 := r + if unicode.IsLetter(r) && unicode.IsLower(r) { + r = unicode.ToUpper(r) + if unicode.ToLower(r) != r1 { + fmt.Printf("cap? %c %c\n", r1, r) + } + } + runes[n-1-i] = r + } + return "?" + string(runes) + "!" +} + +func TestRandomNoisyPalindromes(t *testing.T) { + // Initialize a pseudo-random number generator. + seed := time.Now().UTC().UnixNano() + t.Logf("Random seed: %d", seed) + rng := rand.New(rand.NewSource(seed)) + + n := 0 + for i := 0; i < 1000; i++ { + p := randomNoisyPalindrome(rng) + if !IsPalindrome(p) { + t.Errorf("IsNoisyPalindrome(%q) = false", p) + n++ + } + } + fmt.Fprintf(os.Stderr, "fail = %d\n", n) +} +*/ diff --git a/vendor/gopl.io/ch12/display/display.go b/vendor/gopl.io/ch12/display/display.go new file mode 100644 index 0000000..933a5b0 --- /dev/null +++ b/vendor/gopl.io/ch12/display/display.go @@ -0,0 +1,90 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 333. + +// Package display provides a means to display structured data. +package display + +import ( + "fmt" + "reflect" + "strconv" +) + +//!+Display + +func Display(name string, x interface{}) { + fmt.Printf("Display %s (%T):\n", name, x) + display(name, reflect.ValueOf(x)) +} + +//!-Display + +// formatAtom formats a value without inspecting its internal structure. +// It is a copy of the the function in gopl.io/ch11/format. +func formatAtom(v reflect.Value) string { + switch v.Kind() { + case reflect.Invalid: + return "invalid" + case reflect.Int, reflect.Int8, reflect.Int16, + reflect.Int32, reflect.Int64: + return strconv.FormatInt(v.Int(), 10) + case reflect.Uint, reflect.Uint8, reflect.Uint16, + reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return strconv.FormatUint(v.Uint(), 10) + // ...floating-point and complex cases omitted for brevity... + case reflect.Bool: + if v.Bool() { + return "true" + } + return "false" + case reflect.String: + return strconv.Quote(v.String()) + case reflect.Chan, reflect.Func, reflect.Ptr, + reflect.Slice, reflect.Map: + return v.Type().String() + " 0x" + + strconv.FormatUint(uint64(v.Pointer()), 16) + default: // reflect.Array, reflect.Struct, reflect.Interface + return v.Type().String() + " value" + } +} + +//!+display +func display(path string, v reflect.Value) { + switch v.Kind() { + case reflect.Invalid: + fmt.Printf("%s = invalid\n", path) + case reflect.Slice, reflect.Array: + for i := 0; i < v.Len(); i++ { + display(fmt.Sprintf("%s[%d]", path, i), v.Index(i)) + } + case reflect.Struct: + for i := 0; i < v.NumField(); i++ { + fieldPath := fmt.Sprintf("%s.%s", path, v.Type().Field(i).Name) + display(fieldPath, v.Field(i)) + } + case reflect.Map: + for _, key := range v.MapKeys() { + display(fmt.Sprintf("%s[%s]", path, + formatAtom(key)), v.MapIndex(key)) + } + case reflect.Ptr: + if v.IsNil() { + fmt.Printf("%s = nil\n", path) + } else { + display(fmt.Sprintf("(*%s)", path), v.Elem()) + } + case reflect.Interface: + if v.IsNil() { + fmt.Printf("%s = nil\n", path) + } else { + fmt.Printf("%s.type = %s\n", path, v.Elem().Type()) + display(path+".value", v.Elem()) + } + default: // basic types, channels, funcs + fmt.Printf("%s = %s\n", path, formatAtom(v)) + } +} + +//!-display diff --git a/vendor/gopl.io/ch12/display/display_test.go b/vendor/gopl.io/ch12/display/display_test.go new file mode 100644 index 0000000..bc847ce --- /dev/null +++ b/vendor/gopl.io/ch12/display/display_test.go @@ -0,0 +1,259 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package display + +import ( + "io" + "net" + "os" + "reflect" + "sync" + "testing" + + "gopl.io/ch7/eval" +) + +// NOTE: we can't use !+..!- comments to excerpt these tests +// into the book because it defeats the Example mechanism, +// which requires the // Output comment to be at the end +// of the function. + +func Example_expr() { + e, _ := eval.Parse("sqrt(A / pi)") + Display("e", e) + // Output: + // Display e (eval.call): + // e.fn = "sqrt" + // e.args[0].type = eval.binary + // e.args[0].value.op = 47 + // e.args[0].value.x.type = eval.Var + // e.args[0].value.x.value = "A" + // e.args[0].value.y.type = eval.Var + // e.args[0].value.y.value = "pi" +} + +func Example_slice() { + Display("slice", []*int{new(int), nil}) + // Output: + // Display slice ([]*int): + // (*slice[0]) = 0 + // slice[1] = nil +} + +func Example_nilInterface() { + var w io.Writer + Display("w", w) + // Output: + // Display w (): + // w = invalid +} + +func Example_ptrToInterface() { + var w io.Writer + Display("&w", &w) + // Output: + // Display &w (*io.Writer): + // (*&w) = nil +} + +func Example_struct() { + Display("x", struct{ x interface{} }{3}) + // Output: + // Display x (struct { x interface {} }): + // x.x.type = int + // x.x.value = 3 +} + +func Example_interface() { + var i interface{} = 3 + Display("i", i) + // Output: + // Display i (int): + // i = 3 +} + +func Example_ptrToInterface2() { + var i interface{} = 3 + Display("&i", &i) + // Output: + // Display &i (*interface {}): + // (*&i).type = int + // (*&i).value = 3 +} + +func Example_array() { + Display("x", [1]interface{}{3}) + // Output: + // Display x ([1]interface {}): + // x[0].type = int + // x[0].value = 3 +} + +func Example_movie() { + //!+movie + type Movie struct { + Title, Subtitle string + Year int + Color bool + Actor map[string]string + Oscars []string + Sequel *string + } + //!-movie + //!+strangelove + strangelove := Movie{ + Title: "Dr. Strangelove", + Subtitle: "How I Learned to Stop Worrying and Love the Bomb", + Year: 1964, + Color: false, + Actor: map[string]string{ + "Dr. Strangelove": "Peter Sellers", + "Grp. Capt. Lionel Mandrake": "Peter Sellers", + "Pres. Merkin Muffley": "Peter Sellers", + "Gen. Buck Turgidson": "George C. Scott", + "Brig. Gen. Jack D. Ripper": "Sterling Hayden", + `Maj. T.J. "King" Kong`: "Slim Pickens", + }, + + Oscars: []string{ + "Best Actor (Nomin.)", + "Best Adapted Screenplay (Nomin.)", + "Best Director (Nomin.)", + "Best Picture (Nomin.)", + }, + } + //!-strangelove + Display("strangelove", strangelove) + + // We don't use an Output: comment since displaying + // a map is nondeterministic. + /* + //!+output + Display strangelove (display.Movie): + strangelove.Title = "Dr. Strangelove" + strangelove.Subtitle = "How I Learned to Stop Worrying and Love the Bomb" + strangelove.Year = 1964 + strangelove.Color = false + strangelove.Actor["Gen. Buck Turgidson"] = "George C. Scott" + strangelove.Actor["Brig. Gen. Jack D. Ripper"] = "Sterling Hayden" + strangelove.Actor["Maj. T.J. \"King\" Kong"] = "Slim Pickens" + strangelove.Actor["Dr. Strangelove"] = "Peter Sellers" + strangelove.Actor["Grp. Capt. Lionel Mandrake"] = "Peter Sellers" + strangelove.Actor["Pres. Merkin Muffley"] = "Peter Sellers" + strangelove.Oscars[0] = "Best Actor (Nomin.)" + strangelove.Oscars[1] = "Best Adapted Screenplay (Nomin.)" + strangelove.Oscars[2] = "Best Director (Nomin.)" + strangelove.Oscars[3] = "Best Picture (Nomin.)" + strangelove.Sequel = nil + //!-output + */ +} + +// This test ensures that the program terminates without crashing. +func Test(t *testing.T) { + // Some other values (YMMV) + Display("os.Stderr", os.Stderr) + // Output: + // Display os.Stderr (*os.File): + // (*(*os.Stderr).file).fd = 2 + // (*(*os.Stderr).file).name = "/dev/stderr" + // (*(*os.Stderr).file).nepipe = 0 + + var w io.Writer = os.Stderr + Display("&w", &w) + // Output: + // Display &w (*io.Writer): + // (*&w).type = *os.File + // (*(*(*&w).value).file).fd = 2 + // (*(*(*&w).value).file).name = "/dev/stderr" + // (*(*(*&w).value).file).nepipe = 0 + + var locker sync.Locker = new(sync.Mutex) + Display("(&locker)", &locker) + // Output: + // Display (&locker) (*sync.Locker): + // (*(&locker)).type = *sync.Mutex + // (*(*(&locker)).value).state = 0 + // (*(*(&locker)).value).sema = 0 + + Display("locker", locker) + // Output: + // Display locker (*sync.Mutex): + // (*locker).state = 0 + // (*locker).sema = 0 + // (*(&locker)) = nil + + locker = nil + Display("(&locker)", &locker) + // Output: + // Display (&locker) (*sync.Locker): + // (*(&locker)) = nil + + ips, _ := net.LookupHost("golang.org") + Display("ips", ips) + // Output: + // Display ips ([]string): + // ips[0] = "173.194.68.141" + // ips[1] = "2607:f8b0:400d:c06::8d" + + // Even metarecursion! (YMMV) + Display("rV", reflect.ValueOf(os.Stderr)) + // Output: + // Display rV (reflect.Value): + // (*rV.typ).size = 8 + // (*rV.typ).ptrdata = 8 + // (*rV.typ).hash = 871609668 + // (*rV.typ)._ = 0 + // ... + + // a pointer that points to itself + type P *P + var p P + p = &p + if false { + Display("p", p) + // Output: + // Display p (display.P): + // ...stuck, no output... + } + + // a map that contains itself + type M map[string]M + m := make(M) + m[""] = m + if false { + Display("m", m) + // Output: + // Display m (display.M): + // ...stuck, no output... + } + + // a slice that contains itself + type S []S + s := make(S, 1) + s[0] = s + if false { + Display("s", s) + // Output: + // Display s (display.S): + // ...stuck, no output... + } + + // a linked list that eats its own tail + type Cycle struct { + Value int + Tail *Cycle + } + var c Cycle + c = Cycle{42, &c} + if false { + Display("c", c) + // Output: + // Display c (display.Cycle): + // c.Value = 42 + // (*c.Tail).Value = 42 + // (*(*c.Tail).Tail).Value = 42 + // ...ad infinitum... + } +} diff --git a/vendor/gopl.io/ch12/format/format.go b/vendor/gopl.io/ch12/format/format.go new file mode 100644 index 0000000..02f839a --- /dev/null +++ b/vendor/gopl.io/ch12/format/format.go @@ -0,0 +1,44 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 332. + +// Package format provides an Any function that can format any value. +//!+ +package format + +import ( + "reflect" + "strconv" +) + +// Any formats any value as a string. +func Any(value interface{}) string { + return formatAtom(reflect.ValueOf(value)) +} + +// formatAtom formats a value without inspecting its internal structure. +func formatAtom(v reflect.Value) string { + switch v.Kind() { + case reflect.Invalid: + return "invalid" + case reflect.Int, reflect.Int8, reflect.Int16, + reflect.Int32, reflect.Int64: + return strconv.FormatInt(v.Int(), 10) + case reflect.Uint, reflect.Uint8, reflect.Uint16, + reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return strconv.FormatUint(v.Uint(), 10) + // ...floating-point and complex cases omitted for brevity... + case reflect.Bool: + return strconv.FormatBool(v.Bool()) + case reflect.String: + return strconv.Quote(v.String()) + case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Slice, reflect.Map: + return v.Type().String() + " 0x" + + strconv.FormatUint(uint64(v.Pointer()), 16) + default: // reflect.Array, reflect.Struct, reflect.Interface + return v.Type().String() + " value" + } +} + +//!- diff --git a/vendor/gopl.io/ch12/format/format_test.go b/vendor/gopl.io/ch12/format/format_test.go new file mode 100644 index 0000000..77c0846 --- /dev/null +++ b/vendor/gopl.io/ch12/format/format_test.go @@ -0,0 +1,24 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package format_test + +import ( + "fmt" + "testing" + "time" + + "gopl.io/ch12/format" +) + +func Test(t *testing.T) { + // The pointer values are just examples, and may vary from run to run. + //!+time + var x int64 = 1 + var d time.Duration = 1 * time.Nanosecond + fmt.Println(format.Any(x)) // "1" + fmt.Println(format.Any(d)) // "1" + fmt.Println(format.Any([]int64{x})) // "[]int64 0x8202b87b0" + fmt.Println(format.Any([]time.Duration{d})) // "[]time.Duration 0x8202b87e0" + //!-time +} diff --git a/vendor/gopl.io/ch12/methods/methods.go b/vendor/gopl.io/ch12/methods/methods.go new file mode 100644 index 0000000..3b6b560 --- /dev/null +++ b/vendor/gopl.io/ch12/methods/methods.go @@ -0,0 +1,29 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 351. + +// Package methods provides a function to print the methods of any value. +package methods + +import ( + "fmt" + "reflect" + "strings" +) + +//!+print +// Print prints the method set of the value x. +func Print(x interface{}) { + v := reflect.ValueOf(x) + t := v.Type() + fmt.Printf("type %s\n", t) + + for i := 0; i < v.NumMethod(); i++ { + methType := v.Method(i).Type() + fmt.Printf("func (%s) %s%s\n", t, t.Method(i).Name, + strings.TrimPrefix(methType.String(), "func")) + } +} + +//!-print diff --git a/vendor/gopl.io/ch12/methods/methods_test.go b/vendor/gopl.io/ch12/methods/methods_test.go new file mode 100644 index 0000000..0b509fe --- /dev/null +++ b/vendor/gopl.io/ch12/methods/methods_test.go @@ -0,0 +1,49 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package methods_test + +import ( + "strings" + "time" + + "gopl.io/ch12/methods" +) + +func ExamplePrintDuration() { + methods.Print(time.Hour) + // Output: + // type time.Duration + // func (time.Duration) Hours() float64 + // func (time.Duration) Minutes() float64 + // func (time.Duration) Nanoseconds() int64 + // func (time.Duration) Seconds() float64 + // func (time.Duration) String() string +} + +func ExamplePrintReplacer() { + methods.Print(new(strings.Replacer)) + // Output: + // type *strings.Replacer + // func (*strings.Replacer) Replace(string) string + // func (*strings.Replacer) WriteString(io.Writer, string) (int, error) +} + +/* +//!+output +methods.Print(time.Hour) +// Output: +// type time.Duration +// func (time.Duration) Hours() float64 +// func (time.Duration) Minutes() float64 +// func (time.Duration) Nanoseconds() int64 +// func (time.Duration) Seconds() float64 +// func (time.Duration) String() string + +methods.Print(new(strings.Replacer)) +// Output: +// type *strings.Replacer +// func (*strings.Replacer) Replace(string) string +// func (*strings.Replacer) WriteString(io.Writer, string) (int, error) +//!-output +*/ diff --git a/vendor/gopl.io/ch12/params/params.go b/vendor/gopl.io/ch12/params/params.go new file mode 100644 index 0000000..8bf48cb --- /dev/null +++ b/vendor/gopl.io/ch12/params/params.go @@ -0,0 +1,90 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 349. + +// Package params provides a reflection-based parser for URL parameters. +package params + +import ( + "fmt" + "net/http" + "reflect" + "strconv" + "strings" +) + +//!+Unpack + +// Unpack populates the fields of the struct pointed to by ptr +// from the HTTP request parameters in req. +func Unpack(req *http.Request, ptr interface{}) error { + if err := req.ParseForm(); err != nil { + return err + } + + // Build map of fields keyed by effective name. + fields := make(map[string]reflect.Value) + v := reflect.ValueOf(ptr).Elem() // the struct variable + for i := 0; i < v.NumField(); i++ { + fieldInfo := v.Type().Field(i) // a reflect.StructField + tag := fieldInfo.Tag // a reflect.StructTag + name := tag.Get("http") + if name == "" { + name = strings.ToLower(fieldInfo.Name) + } + fields[name] = v.Field(i) + } + + // Update struct field for each parameter in the request. + for name, values := range req.Form { + f := fields[name] + if !f.IsValid() { + continue // ignore unrecognized HTTP parameters + } + for _, value := range values { + if f.Kind() == reflect.Slice { + elem := reflect.New(f.Type().Elem()).Elem() + if err := populate(elem, value); err != nil { + return fmt.Errorf("%s: %v", name, err) + } + f.Set(reflect.Append(f, elem)) + } else { + if err := populate(f, value); err != nil { + return fmt.Errorf("%s: %v", name, err) + } + } + } + } + return nil +} + +//!-Unpack + +//!+populate +func populate(v reflect.Value, value string) error { + switch v.Kind() { + case reflect.String: + v.SetString(value) + + case reflect.Int: + i, err := strconv.ParseInt(value, 10, 64) + if err != nil { + return err + } + v.SetInt(i) + + case reflect.Bool: + b, err := strconv.ParseBool(value) + if err != nil { + return err + } + v.SetBool(b) + + default: + return fmt.Errorf("unsupported kind %s", v.Type()) + } + return nil +} + +//!-populate diff --git a/vendor/gopl.io/ch12/search/main.go b/vendor/gopl.io/ch12/search/main.go new file mode 100644 index 0000000..9a94e82 --- /dev/null +++ b/vendor/gopl.io/ch12/search/main.go @@ -0,0 +1,60 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 348. + +// Search is a demo of the params.Unpack function. +package main + +import ( + "fmt" + "log" + "net/http" +) + +//!+ + +import "gopl.io/ch12/params" + +// search implements the /search URL endpoint. +func search(resp http.ResponseWriter, req *http.Request) { + var data struct { + Labels []string `http:"l"` + MaxResults int `http:"max"` + Exact bool `http:"x"` + } + data.MaxResults = 10 // set default + if err := params.Unpack(req, &data); err != nil { + http.Error(resp, err.Error(), http.StatusBadRequest) // 400 + return + } + + // ...rest of handler... + fmt.Fprintf(resp, "Search: %+v\n", data) +} + +//!- + +func main() { + http.HandleFunc("/search", search) + log.Fatal(http.ListenAndServe(":12345", nil)) +} + +/* +//!+output +$ go build gopl.io/ch12/search +$ ./search & +$ ./fetch 'http://localhost:12345/search' +Search: {Labels:[] MaxResults:10 Exact:false} +$ ./fetch 'http://localhost:12345/search?l=golang&l=programming' +Search: {Labels:[golang programming] MaxResults:10 Exact:false} +$ ./fetch 'http://localhost:12345/search?l=golang&l=programming&max=100' +Search: {Labels:[golang programming] MaxResults:100 Exact:false} +$ ./fetch 'http://localhost:12345/search?x=true&l=golang&l=programming' +Search: {Labels:[golang programming] MaxResults:10 Exact:true} +$ ./fetch 'http://localhost:12345/search?q=hello&x=123' +x: strconv.ParseBool: parsing "123": invalid syntax +$ ./fetch 'http://localhost:12345/search?q=hello&max=lots' +max: strconv.ParseInt: parsing "lots": invalid syntax +//!-output +*/ diff --git a/vendor/gopl.io/ch12/sexpr/decode.go b/vendor/gopl.io/ch12/sexpr/decode.go new file mode 100644 index 0000000..696e5bc --- /dev/null +++ b/vendor/gopl.io/ch12/sexpr/decode.go @@ -0,0 +1,162 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 344. + +// Package sexpr provides a means for converting Go objects to and +// from S-expressions. +package sexpr + +import ( + "bytes" + "fmt" + "reflect" + "strconv" + "text/scanner" +) + +//!+Unmarshal +// Unmarshal parses S-expression data and populates the variable +// whose address is in the non-nil pointer out. +func Unmarshal(data []byte, out interface{}) (err error) { + lex := &lexer{scan: scanner.Scanner{Mode: scanner.GoTokens}} + lex.scan.Init(bytes.NewReader(data)) + lex.next() // get the first token + defer func() { + // NOTE: this is not an example of ideal error handling. + if x := recover(); x != nil { + err = fmt.Errorf("error at %s: %v", lex.scan.Position, x) + } + }() + read(lex, reflect.ValueOf(out).Elem()) + return nil +} + +//!-Unmarshal + +//!+lexer +type lexer struct { + scan scanner.Scanner + token rune // the current token +} + +func (lex *lexer) next() { lex.token = lex.scan.Scan() } +func (lex *lexer) text() string { return lex.scan.TokenText() } + +func (lex *lexer) consume(want rune) { + if lex.token != want { // NOTE: Not an example of good error handling. + panic(fmt.Sprintf("got %q, want %q", lex.text(), want)) + } + lex.next() +} + +//!-lexer + +// The read function is a decoder for a small subset of well-formed +// S-expressions. For brevity of our example, it takes many dubious +// shortcuts. +// +// The parser assumes +// - that the S-expression input is well-formed; it does no error checking. +// - that the S-expression input corresponds to the type of the variable. +// - that all numbers in the input are non-negative decimal integers. +// - that all keys in ((key value) ...) struct syntax are unquoted symbols. +// - that the input does not contain dotted lists such as (1 2 . 3). +// - that the input does not contain Lisp reader macros such 'x and #'x. +// +// The reflection logic assumes +// - that v is always a variable of the appropriate type for the +// S-expression value. For example, v must not be a boolean, +// interface, channel, or function, and if v is an array, the input +// must have the correct number of elements. +// - that v in the top-level call to read has the zero value of its +// type and doesn't need clearing. +// - that if v is a numeric variable, it is a signed integer. + +//!+read +func read(lex *lexer, v reflect.Value) { + switch lex.token { + case scanner.Ident: + // The only valid identifiers are + // "nil" and struct field names. + if lex.text() == "nil" { + v.Set(reflect.Zero(v.Type())) + lex.next() + return + } + case scanner.String: + s, _ := strconv.Unquote(lex.text()) // NOTE: ignoring errors + v.SetString(s) + lex.next() + return + case scanner.Int: + i, _ := strconv.Atoi(lex.text()) // NOTE: ignoring errors + v.SetInt(int64(i)) + lex.next() + return + case '(': + lex.next() + readList(lex, v) + lex.next() // consume ')' + return + } + panic(fmt.Sprintf("unexpected token %q", lex.text())) +} + +//!-read + +//!+readlist +func readList(lex *lexer, v reflect.Value) { + switch v.Kind() { + case reflect.Array: // (item ...) + for i := 0; !endList(lex); i++ { + read(lex, v.Index(i)) + } + + case reflect.Slice: // (item ...) + for !endList(lex) { + item := reflect.New(v.Type().Elem()).Elem() + read(lex, item) + v.Set(reflect.Append(v, item)) + } + + case reflect.Struct: // ((name value) ...) + for !endList(lex) { + lex.consume('(') + if lex.token != scanner.Ident { + panic(fmt.Sprintf("got token %q, want field name", lex.text())) + } + name := lex.text() + lex.next() + read(lex, v.FieldByName(name)) + lex.consume(')') + } + + case reflect.Map: // ((key value) ...) + v.Set(reflect.MakeMap(v.Type())) + for !endList(lex) { + lex.consume('(') + key := reflect.New(v.Type().Key()).Elem() + read(lex, key) + value := reflect.New(v.Type().Elem()).Elem() + read(lex, value) + v.SetMapIndex(key, value) + lex.consume(')') + } + + default: + panic(fmt.Sprintf("cannot decode list into %v", v.Type())) + } +} + +func endList(lex *lexer) bool { + switch lex.token { + case scanner.EOF: + panic("end of file") + case ')': + return true + } + return false +} + +//!-readlist diff --git a/vendor/gopl.io/ch12/sexpr/encode.go b/vendor/gopl.io/ch12/sexpr/encode.go new file mode 100644 index 0000000..f2a53a0 --- /dev/null +++ b/vendor/gopl.io/ch12/sexpr/encode.go @@ -0,0 +1,97 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 339. + +package sexpr + +import ( + "bytes" + "fmt" + "reflect" +) + +//!+Marshal +// Marshal encodes a Go value in S-expression form. +func Marshal(v interface{}) ([]byte, error) { + var buf bytes.Buffer + if err := encode(&buf, reflect.ValueOf(v)); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +//!-Marshal + +// encode writes to buf an S-expression representation of v. +//!+encode +func encode(buf *bytes.Buffer, v reflect.Value) error { + switch v.Kind() { + case reflect.Invalid: + buf.WriteString("nil") + + case reflect.Int, reflect.Int8, reflect.Int16, + reflect.Int32, reflect.Int64: + fmt.Fprintf(buf, "%d", v.Int()) + + case reflect.Uint, reflect.Uint8, reflect.Uint16, + reflect.Uint32, reflect.Uint64, reflect.Uintptr: + fmt.Fprintf(buf, "%d", v.Uint()) + + case reflect.String: + fmt.Fprintf(buf, "%q", v.String()) + + case reflect.Ptr: + return encode(buf, v.Elem()) + + case reflect.Array, reflect.Slice: // (value ...) + buf.WriteByte('(') + for i := 0; i < v.Len(); i++ { + if i > 0 { + buf.WriteByte(' ') + } + if err := encode(buf, v.Index(i)); err != nil { + return err + } + } + buf.WriteByte(')') + + case reflect.Struct: // ((name value) ...) + buf.WriteByte('(') + for i := 0; i < v.NumField(); i++ { + if i > 0 { + buf.WriteByte(' ') + } + fmt.Fprintf(buf, "(%s ", v.Type().Field(i).Name) + if err := encode(buf, v.Field(i)); err != nil { + return err + } + buf.WriteByte(')') + } + buf.WriteByte(')') + + case reflect.Map: // ((key value) ...) + buf.WriteByte('(') + for i, key := range v.MapKeys() { + if i > 0 { + buf.WriteByte(' ') + } + buf.WriteByte('(') + if err := encode(buf, key); err != nil { + return err + } + buf.WriteByte(' ') + if err := encode(buf, v.MapIndex(key)); err != nil { + return err + } + buf.WriteByte(')') + } + buf.WriteByte(')') + + default: // float, complex, bool, chan, func, interface + return fmt.Errorf("unsupported type: %s", v.Type()) + } + return nil +} + +//!-encode diff --git a/vendor/gopl.io/ch12/sexpr/pretty.go b/vendor/gopl.io/ch12/sexpr/pretty.go new file mode 100644 index 0000000..1c5716d --- /dev/null +++ b/vendor/gopl.io/ch12/sexpr/pretty.go @@ -0,0 +1,183 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package sexpr + +// This file implements the algorithm described in Derek C. Oppen's +// 1979 Stanford technical report, "Pretty Printing". + +import ( + "bytes" + "fmt" + "reflect" +) + +func MarshalIndent(v interface{}) ([]byte, error) { + p := printer{width: margin} + if err := pretty(&p, reflect.ValueOf(v)); err != nil { + return nil, err + } + return p.Bytes(), nil +} + +const margin = 80 + +type token struct { + kind rune // one of "s ()" (string, blank, start, end) + str string + size int +} + +type printer struct { + tokens []*token // FIFO buffer + stack []*token // stack of open ' ' and '(' tokens + rtotal int // total number of spaces needed to print stream + + bytes.Buffer + indents []int + width int // remaining space +} + +func (p *printer) string(str string) { + tok := &token{kind: 's', str: str, size: len(str)} + if len(p.stack) == 0 { + p.print(tok) + } else { + p.tokens = append(p.tokens, tok) + p.rtotal += len(str) + } +} +func (p *printer) pop() (top *token) { + last := len(p.stack) - 1 + top, p.stack = p.stack[last], p.stack[:last] + return +} +func (p *printer) begin() { + if len(p.stack) == 0 { + p.rtotal = 1 + } + t := &token{kind: '(', size: -p.rtotal} + p.tokens = append(p.tokens, t) + p.stack = append(p.stack, t) // push + p.string("(") +} +func (p *printer) end() { + p.string(")") + p.tokens = append(p.tokens, &token{kind: ')'}) + x := p.pop() + x.size += p.rtotal + if x.kind == ' ' { + p.pop().size += p.rtotal + } + if len(p.stack) == 0 { + for _, tok := range p.tokens { + p.print(tok) + } + p.tokens = nil + } +} +func (p *printer) space() { + last := len(p.stack) - 1 + x := p.stack[last] + if x.kind == ' ' { + x.size += p.rtotal + p.stack = p.stack[:last] // pop + } + t := &token{kind: ' ', size: -p.rtotal} + p.tokens = append(p.tokens, t) + p.stack = append(p.stack, t) + p.rtotal++ +} +func (p *printer) print(t *token) { + switch t.kind { + case 's': + p.WriteString(t.str) + p.width -= len(t.str) + case '(': + p.indents = append(p.indents, p.width) + case ')': + p.indents = p.indents[:len(p.indents)-1] // pop + case ' ': + if t.size > p.width { + p.width = p.indents[len(p.indents)-1] - 1 + fmt.Fprintf(&p.Buffer, "\n%*s", margin-p.width, "") + } else { + p.WriteByte(' ') + p.width-- + } + } +} +func (p *printer) stringf(format string, args ...interface{}) { + p.string(fmt.Sprintf(format, args...)) +} + +func pretty(p *printer, v reflect.Value) error { + switch v.Kind() { + case reflect.Invalid: + p.string("nil") + + case reflect.Int, reflect.Int8, reflect.Int16, + reflect.Int32, reflect.Int64: + p.stringf("%d", v.Int()) + + case reflect.Uint, reflect.Uint8, reflect.Uint16, + reflect.Uint32, reflect.Uint64, reflect.Uintptr: + p.stringf("%d", v.Uint()) + + case reflect.String: + p.stringf("%q", v.String()) + + case reflect.Array, reflect.Slice: // (value ...) + p.begin() + for i := 0; i < v.Len(); i++ { + if i > 0 { + p.space() + } + if err := pretty(p, v.Index(i)); err != nil { + return err + } + } + p.end() + + case reflect.Struct: // ((name value ...) + p.begin() + for i := 0; i < v.NumField(); i++ { + if i > 0 { + p.space() + } + p.begin() + p.string(v.Type().Field(i).Name) + p.space() + if err := pretty(p, v.Field(i)); err != nil { + return err + } + p.end() + } + p.end() + + case reflect.Map: // ((key value ...) + p.begin() + for i, key := range v.MapKeys() { + if i > 0 { + p.space() + } + p.begin() + if err := pretty(p, key); err != nil { + return err + } + p.space() + if err := pretty(p, v.MapIndex(key)); err != nil { + return err + } + p.end() + } + p.end() + + case reflect.Ptr: + return pretty(p, v.Elem()) + + default: // float, complex, bool, chan, func, interface + return fmt.Errorf("unsupported type: %s", v.Type()) + } + return nil +} diff --git a/vendor/gopl.io/ch12/sexpr/sexpr_test.go b/vendor/gopl.io/ch12/sexpr/sexpr_test.go new file mode 100644 index 0000000..25b0bf7 --- /dev/null +++ b/vendor/gopl.io/ch12/sexpr/sexpr_test.go @@ -0,0 +1,74 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package sexpr + +import ( + "reflect" + "testing" +) + +// Test verifies that encoding and decoding a complex data value +// produces an equal result. +// +// The test does not make direct assertions about the encoded output +// because the output depends on map iteration order, which is +// nondeterministic. The output of the t.Log statements can be +// inspected by running the test with the -v flag: +// +// $ go test -v gopl.io/ch12/sexpr +// +func Test(t *testing.T) { + type Movie struct { + Title, Subtitle string + Year int + Actor map[string]string + Oscars []string + Sequel *string + } + strangelove := Movie{ + Title: "Dr. Strangelove", + Subtitle: "How I Learned to Stop Worrying and Love the Bomb", + Year: 1964, + Actor: map[string]string{ + "Dr. Strangelove": "Peter Sellers", + "Grp. Capt. Lionel Mandrake": "Peter Sellers", + "Pres. Merkin Muffley": "Peter Sellers", + "Gen. Buck Turgidson": "George C. Scott", + "Brig. Gen. Jack D. Ripper": "Sterling Hayden", + `Maj. T.J. "King" Kong`: "Slim Pickens", + }, + Oscars: []string{ + "Best Actor (Nomin.)", + "Best Adapted Screenplay (Nomin.)", + "Best Director (Nomin.)", + "Best Picture (Nomin.)", + }, + } + + // Encode it + data, err := Marshal(strangelove) + if err != nil { + t.Fatalf("Marshal failed: %v", err) + } + t.Logf("Marshal() = %s\n", data) + + // Decode it + var movie Movie + if err := Unmarshal(data, &movie); err != nil { + t.Fatalf("Unmarshal failed: %v", err) + } + t.Logf("Unmarshal() = %+v\n", movie) + + // Check equality. + if !reflect.DeepEqual(movie, strangelove) { + t.Fatal("not equal") + } + + // Pretty-print it: + data, err = MarshalIndent(strangelove) + if err != nil { + t.Fatal(err) + } + t.Logf("MarshalIdent() = %s\n", data) +} diff --git a/vendor/gopl.io/ch13/bzip-print/bzip2.c b/vendor/gopl.io/ch13/bzip-print/bzip2.c new file mode 100644 index 0000000..42a3a53 --- /dev/null +++ b/vendor/gopl.io/ch13/bzip-print/bzip2.c @@ -0,0 +1,28 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 362. +// This is the version that appears in print, +// but it does not comply with the proposed +// rules for passing pointers between Go and C. +// (https://github.com/golang/proposal/blob/master/design/12416-cgo-pointers.md) +// See gopl.io/ch13/bzip for an updated version. + +//!+ +/* This file is gopl.io/ch13/bzip/bzip2.c, */ +/* a simple wrapper for libbzip2 suitable for cgo. */ +#include + +int bz2compress(bz_stream *s, int action, + char *in, unsigned *inlen, char *out, unsigned *outlen) { + s->next_in = in; + s->avail_in = *inlen; + s->next_out = out; + s->avail_out = *outlen; + int r = BZ2_bzCompress(s, action); + *inlen -= s->avail_in; + *outlen -= s->avail_out; + return r; +} + +//!- diff --git a/vendor/gopl.io/ch13/bzip-print/bzip2.go b/vendor/gopl.io/ch13/bzip-print/bzip2.go new file mode 100644 index 0000000..1d8c771 --- /dev/null +++ b/vendor/gopl.io/ch13/bzip-print/bzip2.go @@ -0,0 +1,96 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 362. +// This is the version that appears in print, +// but it does not comply with the proposed +// rules for passing pointers between Go and C. +// (https://github.com/golang/proposal/blob/master/design/12416-cgo-pointers.md) +// See gopl.io/ch13/bzip for an updated version. +//!+ + +// Package bzip provides a writer that uses bzip2 compression (bzip.org). +package bzip + +/* +#cgo CFLAGS: -I/usr/include +#cgo LDFLAGS: -L/usr/lib -lbz2 +#include +int bz2compress(bz_stream *s, int action, + char *in, unsigned *inlen, char *out, unsigned *outlen); +*/ +import "C" + +import ( + "io" + "unsafe" +) + +type writer struct { + w io.Writer // underlying output stream + stream *C.bz_stream + outbuf [64 * 1024]byte +} + +// NewWriter returns a writer for bzip2-compressed streams. +func NewWriter(out io.Writer) io.WriteCloser { + const ( + blockSize = 9 + verbosity = 0 + workFactor = 30 + ) + w := &writer{w: out, stream: new(C.bz_stream)} + C.BZ2_bzCompressInit(w.stream, blockSize, verbosity, workFactor) + return w +} + +//!- + +//!+write +func (w *writer) Write(data []byte) (int, error) { + if w.stream == nil { + panic("closed") + } + var total int // uncompressed bytes written + + for len(data) > 0 { + inlen, outlen := C.uint(len(data)), C.uint(cap(w.outbuf)) + C.bz2compress(w.stream, C.BZ_RUN, + (*C.char)(unsafe.Pointer(&data[0])), &inlen, + (*C.char)(unsafe.Pointer(&w.outbuf)), &outlen) + total += int(inlen) + data = data[inlen:] + if _, err := w.w.Write(w.outbuf[:outlen]); err != nil { + return total, err + } + } + return total, nil +} + +//!-write + +//!+close +// Close flushes the compressed data and closes the stream. +// It does not close the underlying io.Writer. +func (w *writer) Close() error { + if w.stream == nil { + panic("closed") + } + defer func() { + C.BZ2_bzCompressEnd(w.stream) + w.stream = nil + }() + for { + inlen, outlen := C.uint(0), C.uint(cap(w.outbuf)) + r := C.bz2compress(w.stream, C.BZ_FINISH, nil, &inlen, + (*C.char)(unsafe.Pointer(&w.outbuf)), &outlen) + if _, err := w.w.Write(w.outbuf[:outlen]); err != nil { + return err + } + if r == C.BZ_STREAM_END { + return nil + } + } +} + +//!-close diff --git a/vendor/gopl.io/ch13/bzip-print/bzip2_test.go b/vendor/gopl.io/ch13/bzip-print/bzip2_test.go new file mode 100644 index 0000000..c52aba0 --- /dev/null +++ b/vendor/gopl.io/ch13/bzip-print/bzip2_test.go @@ -0,0 +1,40 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package bzip_test + +import ( + "bytes" + "compress/bzip2" // reader + "io" + "testing" + + "gopl.io/ch13/bzip" // writer +) + +func TestBzip2(t *testing.T) { + var compressed, uncompressed bytes.Buffer + w := bzip.NewWriter(&compressed) + + // Write a repetitive message in a million pieces, + // compressing one copy but not the other. + tee := io.MultiWriter(w, &uncompressed) + for i := 0; i < 1000000; i++ { + io.WriteString(tee, "hello") + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + + // Check the size of the compressed stream. + if got, want := compressed.Len(), 255; got != want { + t.Errorf("1 million hellos compressed to %d bytes, want %d", got, want) + } + + // Decompress and compare with original. + var decompressed bytes.Buffer + io.Copy(&decompressed, bzip2.NewReader(&compressed)) + if !bytes.Equal(uncompressed.Bytes(), decompressed.Bytes()) { + t.Error("decompression yielded a different message") + } +} diff --git a/vendor/gopl.io/ch13/bzip/bzip2.c b/vendor/gopl.io/ch13/bzip/bzip2.c new file mode 100644 index 0000000..985869e --- /dev/null +++ b/vendor/gopl.io/ch13/bzip/bzip2.c @@ -0,0 +1,32 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 362. +// +// The version of this program that appeared in the first and second +// printings did not comply with the proposed rules for passing +// pointers between Go and C, described here: +// https://github.com/golang/proposal/blob/master/design/12416-cgo-pointers.md +// +// The version below, which appears in the third printing, +// has been corrected. See bzip2.go for explanation. + +//!+ +/* This file is gopl.io/ch13/bzip/bzip2.c, */ +/* a simple wrapper for libbzip2 suitable for cgo. */ +#include + +int bz2compress(bz_stream *s, int action, + char *in, unsigned *inlen, char *out, unsigned *outlen) { + s->next_in = in; + s->avail_in = *inlen; + s->next_out = out; + s->avail_out = *outlen; + int r = BZ2_bzCompress(s, action); + *inlen -= s->avail_in; + *outlen -= s->avail_out; + s->next_in = s->next_out = NULL; + return r; +} + +//!- diff --git a/vendor/gopl.io/ch13/bzip/bzip2.go b/vendor/gopl.io/ch13/bzip/bzip2.go new file mode 100644 index 0000000..278b238 --- /dev/null +++ b/vendor/gopl.io/ch13/bzip/bzip2.go @@ -0,0 +1,111 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 362. +// +// The version of this program that appeared in the first and second +// printings did not comply with the proposed rules for passing +// pointers between Go and C, described here: +// https://github.com/golang/proposal/blob/master/design/12416-cgo-pointers.md +// +// The rules forbid a C function like bz2compress from storing 'in' +// and 'out' (pointers to variables allocated by Go) into the Go +// variable 's', even temporarily. +// +// The version below, which appears in the third printing, has been +// corrected. To comply with the rules, the bz_stream variable must +// be allocated by C code. We have introduced two C functions, +// bz2alloc and bz2free, to allocate and free instances of the +// bz_stream type. Also, we have changed bz2compress so that before +// it returns, it clears the fields of the bz_stream that contain +// pointers to Go variables. + +//!+ + +// Package bzip provides a writer that uses bzip2 compression (bzip.org). +package bzip + +/* +#cgo CFLAGS: -I/usr/include +#cgo LDFLAGS: -L/usr/lib -lbz2 +#include +#include +bz_stream* bz2alloc() { return calloc(1, sizeof(bz_stream)); } +int bz2compress(bz_stream *s, int action, + char *in, unsigned *inlen, char *out, unsigned *outlen); +void bz2free(bz_stream* s) { free(s); } +*/ +import "C" + +import ( + "io" + "unsafe" +) + +type writer struct { + w io.Writer // underlying output stream + stream *C.bz_stream + outbuf [64 * 1024]byte +} + +// NewWriter returns a writer for bzip2-compressed streams. +func NewWriter(out io.Writer) io.WriteCloser { + const blockSize = 9 + const verbosity = 0 + const workFactor = 30 + w := &writer{w: out, stream: C.bz2alloc()} + C.BZ2_bzCompressInit(w.stream, blockSize, verbosity, workFactor) + return w +} + +//!- + +//!+write +func (w *writer) Write(data []byte) (int, error) { + if w.stream == nil { + panic("closed") + } + var total int // uncompressed bytes written + + for len(data) > 0 { + inlen, outlen := C.uint(len(data)), C.uint(cap(w.outbuf)) + C.bz2compress(w.stream, C.BZ_RUN, + (*C.char)(unsafe.Pointer(&data[0])), &inlen, + (*C.char)(unsafe.Pointer(&w.outbuf)), &outlen) + total += int(inlen) + data = data[inlen:] + if _, err := w.w.Write(w.outbuf[:outlen]); err != nil { + return total, err + } + } + return total, nil +} + +//!-write + +//!+close +// Close flushes the compressed data and closes the stream. +// It does not close the underlying io.Writer. +func (w *writer) Close() error { + if w.stream == nil { + panic("closed") + } + defer func() { + C.BZ2_bzCompressEnd(w.stream) + C.bz2free(w.stream) + w.stream = nil + }() + for { + inlen, outlen := C.uint(0), C.uint(cap(w.outbuf)) + r := C.bz2compress(w.stream, C.BZ_FINISH, nil, &inlen, + (*C.char)(unsafe.Pointer(&w.outbuf)), &outlen) + if _, err := w.w.Write(w.outbuf[:outlen]); err != nil { + return err + } + if r == C.BZ_STREAM_END { + return nil + } + } +} + +//!-close diff --git a/vendor/gopl.io/ch13/bzip/bzip2_test.go b/vendor/gopl.io/ch13/bzip/bzip2_test.go new file mode 100644 index 0000000..c52aba0 --- /dev/null +++ b/vendor/gopl.io/ch13/bzip/bzip2_test.go @@ -0,0 +1,40 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package bzip_test + +import ( + "bytes" + "compress/bzip2" // reader + "io" + "testing" + + "gopl.io/ch13/bzip" // writer +) + +func TestBzip2(t *testing.T) { + var compressed, uncompressed bytes.Buffer + w := bzip.NewWriter(&compressed) + + // Write a repetitive message in a million pieces, + // compressing one copy but not the other. + tee := io.MultiWriter(w, &uncompressed) + for i := 0; i < 1000000; i++ { + io.WriteString(tee, "hello") + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + + // Check the size of the compressed stream. + if got, want := compressed.Len(), 255; got != want { + t.Errorf("1 million hellos compressed to %d bytes, want %d", got, want) + } + + // Decompress and compare with original. + var decompressed bytes.Buffer + io.Copy(&decompressed, bzip2.NewReader(&compressed)) + if !bytes.Equal(uncompressed.Bytes(), decompressed.Bytes()) { + t.Error("decompression yielded a different message") + } +} diff --git a/vendor/gopl.io/ch13/bzipper/main.go b/vendor/gopl.io/ch13/bzipper/main.go new file mode 100644 index 0000000..a8ebad1 --- /dev/null +++ b/vendor/gopl.io/ch13/bzipper/main.go @@ -0,0 +1,29 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 365. + +//!+ + +// Bzipper reads input, bzip2-compresses it, and writes it out. +package main + +import ( + "io" + "log" + "os" + + "gopl.io/ch13/bzip" +) + +func main() { + w := bzip.NewWriter(os.Stdout) + if _, err := io.Copy(w, os.Stdin); err != nil { + log.Fatalf("bzipper: %v\n", err) + } + if err := w.Close(); err != nil { + log.Fatalf("bzipper: close: %v\n", err) + } +} + +//!- diff --git a/vendor/gopl.io/ch13/equal/equal.go b/vendor/gopl.io/ch13/equal/equal.go new file mode 100644 index 0000000..ec4b40c --- /dev/null +++ b/vendor/gopl.io/ch13/equal/equal.go @@ -0,0 +1,127 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 359. + +// Package equal provides a deep equivalence relation for arbitrary values. +package equal + +import ( + "reflect" + "unsafe" +) + +//!+ +func equal(x, y reflect.Value, seen map[comparison]bool) bool { + if !x.IsValid() || !y.IsValid() { + return x.IsValid() == y.IsValid() + } + if x.Type() != y.Type() { + return false + } + + // ...cycle check omitted (shown later)... + + //!- + //!+cyclecheck + // cycle check + if x.CanAddr() && y.CanAddr() { + xptr := unsafe.Pointer(x.UnsafeAddr()) + yptr := unsafe.Pointer(y.UnsafeAddr()) + if xptr == yptr { + return true // identical references + } + c := comparison{xptr, yptr, x.Type()} + if seen[c] { + return true // already seen + } + seen[c] = true + } + //!-cyclecheck + //!+ + switch x.Kind() { + case reflect.Bool: + return x.Bool() == y.Bool() + + case reflect.String: + return x.String() == y.String() + + // ...numeric cases omitted for brevity... + + //!- + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, + reflect.Int64: + return x.Int() == y.Int() + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, + reflect.Uint64, reflect.Uintptr: + return x.Uint() == y.Uint() + + case reflect.Float32, reflect.Float64: + return x.Float() == y.Float() + + case reflect.Complex64, reflect.Complex128: + return x.Complex() == y.Complex() + //!+ + case reflect.Chan, reflect.UnsafePointer, reflect.Func: + return x.Pointer() == y.Pointer() + + case reflect.Ptr, reflect.Interface: + return equal(x.Elem(), y.Elem(), seen) + + case reflect.Array, reflect.Slice: + if x.Len() != y.Len() { + return false + } + for i := 0; i < x.Len(); i++ { + if !equal(x.Index(i), y.Index(i), seen) { + return false + } + } + return true + + // ...struct and map cases omitted for brevity... + //!- + case reflect.Struct: + for i, n := 0, x.NumField(); i < n; i++ { + if !equal(x.Field(i), y.Field(i), seen) { + return false + } + } + return true + + case reflect.Map: + if x.Len() != y.Len() { + return false + } + for _, k := range x.MapKeys() { + if !equal(x.MapIndex(k), y.MapIndex(k), seen) { + return false + } + } + return true + //!+ + } + panic("unreachable") +} + +//!- + +//!+comparison +// Equal reports whether x and y are deeply equal. +//!-comparison +// +// Map keys are always compared with ==, not deeply. +// (This matters for keys containing pointers or interfaces.) +//!+comparison +func Equal(x, y interface{}) bool { + seen := make(map[comparison]bool) + return equal(reflect.ValueOf(x), reflect.ValueOf(y), seen) +} + +type comparison struct { + x, y unsafe.Pointer + t reflect.Type +} + +//!-comparison diff --git a/vendor/gopl.io/ch13/equal/equal_test.go b/vendor/gopl.io/ch13/equal/equal_test.go new file mode 100644 index 0000000..4656077 --- /dev/null +++ b/vendor/gopl.io/ch13/equal/equal_test.go @@ -0,0 +1,133 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package equal + +import ( + "bytes" + "fmt" + "testing" +) + +func TestEqual(t *testing.T) { + one, oneAgain, two := 1, 1, 2 + + type CyclePtr *CyclePtr + var cyclePtr1, cyclePtr2 CyclePtr + cyclePtr1 = &cyclePtr1 + cyclePtr2 = &cyclePtr2 + + type CycleSlice []CycleSlice + var cycleSlice CycleSlice + cycleSlice = append(cycleSlice, cycleSlice) + + ch1, ch2 := make(chan int), make(chan int) + var ch1ro <-chan int = ch1 + + type mystring string + + var iface1, iface1Again, iface2 interface{} = &one, &oneAgain, &two + + for _, test := range []struct { + x, y interface{} + want bool + }{ + // basic types + {1, 1, true}, + {1, 2, false}, // different values + {1, 1.0, false}, // different types + {"foo", "foo", true}, + {"foo", "bar", false}, + {mystring("foo"), "foo", false}, // different types + // slices + {[]string{"foo"}, []string{"foo"}, true}, + {[]string{"foo"}, []string{"bar"}, false}, + {[]string{}, []string(nil), true}, + // slice cycles + {cycleSlice, cycleSlice, true}, + // maps + { + map[string][]int{"foo": {1, 2, 3}}, + map[string][]int{"foo": {1, 2, 3}}, + true, + }, + { + map[string][]int{"foo": {1, 2, 3}}, + map[string][]int{"foo": {1, 2, 3, 4}}, + false, + }, + { + map[string][]int{}, + map[string][]int(nil), + true, + }, + // pointers + {&one, &one, true}, + {&one, &two, false}, + {&one, &oneAgain, true}, + {new(bytes.Buffer), new(bytes.Buffer), true}, + // pointer cycles + {cyclePtr1, cyclePtr1, true}, + {cyclePtr2, cyclePtr2, true}, + {cyclePtr1, cyclePtr2, true}, // they're deeply equal + // functions + {(func())(nil), (func())(nil), true}, + {(func())(nil), func() {}, false}, + {func() {}, func() {}, false}, + // arrays + {[...]int{1, 2, 3}, [...]int{1, 2, 3}, true}, + {[...]int{1, 2, 3}, [...]int{1, 2, 4}, false}, + // channels + {ch1, ch1, true}, + {ch1, ch2, false}, + {ch1ro, ch1, false}, // NOTE: not equal + // interfaces + {&iface1, &iface1, true}, + {&iface1, &iface2, false}, + {&iface1Again, &iface1, true}, + } { + if Equal(test.x, test.y) != test.want { + t.Errorf("Equal(%v, %v) = %t", + test.x, test.y, !test.want) + } + } +} + +func Example_equal() { + //!+ + fmt.Println(Equal([]int{1, 2, 3}, []int{1, 2, 3})) // "true" + fmt.Println(Equal([]string{"foo"}, []string{"bar"})) // "false" + fmt.Println(Equal([]string(nil), []string{})) // "true" + fmt.Println(Equal(map[string]int(nil), map[string]int{})) // "true" + //!- + + // Output: + // true + // false + // true + // true +} + +func Example_equalCycle() { + //!+cycle + // Circular linked lists a -> b -> a and c -> c. + type link struct { + value string + tail *link + } + a, b, c := &link{value: "a"}, &link{value: "b"}, &link{value: "c"} + a.tail, b.tail, c.tail = b, a, c + fmt.Println(Equal(a, a)) // "true" + fmt.Println(Equal(b, b)) // "true" + fmt.Println(Equal(c, c)) // "true" + fmt.Println(Equal(a, b)) // "false" + fmt.Println(Equal(a, c)) // "false" + //!-cycle + + // Output: + // true + // true + // true + // false + // false +} diff --git a/vendor/gopl.io/ch13/unsafeptr/main.go b/vendor/gopl.io/ch13/unsafeptr/main.go new file mode 100644 index 0000000..f906946 --- /dev/null +++ b/vendor/gopl.io/ch13/unsafeptr/main.go @@ -0,0 +1,38 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 357. + +// Package unsafeptr demonstrates basic use of unsafe.Pointer. +package main + +import ( + "fmt" + "unsafe" +) + +func main() { + //!+main + var x struct { + a bool + b int16 + c []int + } + + // equivalent to pb := &x.b + pb := (*int16)(unsafe.Pointer( + uintptr(unsafe.Pointer(&x)) + unsafe.Offsetof(x.b))) + *pb = 42 + + fmt.Println(x.b) // "42" + //!-main +} + +/* +//!+wrong + // NOTE: subtly incorrect! + tmp := uintptr(unsafe.Pointer(&x)) + unsafe.Offsetof(x.b) + pb := (*int16)(unsafe.Pointer(tmp)) + *pb = 42 +//!-wrong +*/ diff --git a/vendor/gopl.io/ch2/boiling/main.go b/vendor/gopl.io/ch2/boiling/main.go new file mode 100644 index 0000000..b7a1dbe --- /dev/null +++ b/vendor/gopl.io/ch2/boiling/main.go @@ -0,0 +1,22 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 29. +//!+ + +// Boiling prints the boiling point of water. +package main + +import "fmt" + +const boilingF = 212.0 + +func main() { + var f = boilingF + var c = (f - 32) * 5 / 9 + fmt.Printf("boiling point = %g°F or %g°C\n", f, c) + // Output: + // boiling point = 212°F or 100°C +} + +//!- diff --git a/vendor/gopl.io/ch2/cf/main.go b/vendor/gopl.io/ch2/cf/main.go new file mode 100644 index 0000000..882101f --- /dev/null +++ b/vendor/gopl.io/ch2/cf/main.go @@ -0,0 +1,32 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 43. +//!+ + +// Cf converts its numeric argument to Celsius and Fahrenheit. +package main + +import ( + "fmt" + "os" + "strconv" + + "gopl.io/ch2/tempconv" +) + +func main() { + for _, arg := range os.Args[1:] { + t, err := strconv.ParseFloat(arg, 64) + if err != nil { + fmt.Fprintf(os.Stderr, "cf: %v\n", err) + os.Exit(1) + } + f := tempconv.Fahrenheit(t) + c := tempconv.Celsius(t) + fmt.Printf("%s = %s, %s = %s\n", + f, tempconv.FToC(f), c, tempconv.CToF(c)) + } +} + +//!- diff --git a/vendor/gopl.io/ch2/echo4/main.go b/vendor/gopl.io/ch2/echo4/main.go new file mode 100644 index 0000000..5a029fd --- /dev/null +++ b/vendor/gopl.io/ch2/echo4/main.go @@ -0,0 +1,27 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 33. +//!+ + +// Echo4 prints its command-line arguments. +package main + +import ( + "flag" + "fmt" + "strings" +) + +var n = flag.Bool("n", false, "omit trailing newline") +var sep = flag.String("s", " ", "separator") + +func main() { + flag.Parse() + fmt.Print(strings.Join(flag.Args(), *sep)) + if !*n { + fmt.Println() + } +} + +//!- diff --git a/vendor/gopl.io/ch2/ftoc/main.go b/vendor/gopl.io/ch2/ftoc/main.go new file mode 100644 index 0000000..3f3abd0 --- /dev/null +++ b/vendor/gopl.io/ch2/ftoc/main.go @@ -0,0 +1,22 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 29. +//!+ + +// Ftoc prints two Fahrenheit-to-Celsius conversions. +package main + +import "fmt" + +func main() { + const freezingF, boilingF = 32.0, 212.0 + fmt.Printf("%g°F = %g°C\n", freezingF, fToC(freezingF)) // "32°F = 0°C" + fmt.Printf("%g°F = %g°C\n", boilingF, fToC(boilingF)) // "212°F = 100°C" +} + +func fToC(f float64) float64 { + return (f - 32) * 5 / 9 +} + +//!- diff --git a/vendor/gopl.io/ch2/popcount/main.go b/vendor/gopl.io/ch2/popcount/main.go new file mode 100644 index 0000000..c994e08 --- /dev/null +++ b/vendor/gopl.io/ch2/popcount/main.go @@ -0,0 +1,31 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 45. + +// (Package doc comment intentionally malformed to demonstrate golint.) +//!+ +package popcount + +// pc[i] is the population count of i. +var pc [256]byte + +func init() { + for i := range pc { + pc[i] = pc[i/2] + byte(i&1) + } +} + +// PopCount returns the population count (number of set bits) of x. +func PopCount(x uint64) int { + return int(pc[byte(x>>(0*8))] + + pc[byte(x>>(1*8))] + + pc[byte(x>>(2*8))] + + pc[byte(x>>(3*8))] + + pc[byte(x>>(4*8))] + + pc[byte(x>>(5*8))] + + pc[byte(x>>(6*8))] + + pc[byte(x>>(7*8))]) +} + +//!- diff --git a/vendor/gopl.io/ch2/popcount/popcount_test.go b/vendor/gopl.io/ch2/popcount/popcount_test.go new file mode 100644 index 0000000..504548d --- /dev/null +++ b/vendor/gopl.io/ch2/popcount/popcount_test.go @@ -0,0 +1,83 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package popcount_test + +import ( + "testing" + + "gopl.io/ch2/popcount" +) + +// -- Alternative implementations -- + +func BitCount(x uint64) int { + // Hacker's Delight, Figure 5-2. + x = x - ((x >> 1) & 0x5555555555555555) + x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333) + x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f + x = x + (x >> 8) + x = x + (x >> 16) + x = x + (x >> 32) + return int(x & 0x7f) +} + +func PopCountByClearing(x uint64) int { + n := 0 + for x != 0 { + x = x & (x - 1) // clear rightmost non-zero bit + n++ + } + return n +} + +func PopCountByShifting(x uint64) int { + n := 0 + for i := uint(0); i < 64; i++ { + if x&(1< a, a.go => a, a/b/c.go => c, a/b.c.go => b.c +func basename(s string) string { + // Discard last '/' and everything before. + for i := len(s) - 1; i >= 0; i-- { + if s[i] == '/' { + s = s[i+1:] + break + } + } + // Preserve everything before last '.'. + for i := len(s) - 1; i >= 0; i-- { + if s[i] == '.' { + s = s[:i] + break + } + } + return s +} + +//!- diff --git a/vendor/gopl.io/ch3/basename2/main.go b/vendor/gopl.io/ch3/basename2/main.go new file mode 100644 index 0000000..93c471c --- /dev/null +++ b/vendor/gopl.io/ch3/basename2/main.go @@ -0,0 +1,36 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 72. + +// Basename2 reads file names from stdin and prints the base name of each one. +package main + +import ( + "bufio" + "fmt" + "os" + "strings" +) + +func main() { + input := bufio.NewScanner(os.Stdin) + for input.Scan() { + fmt.Println(basename(input.Text())) + } + // NOTE: ignoring potential errors from input.Err() +} + +// basename removes directory components and a trailing .suffix. +// e.g., a => a, a.go => a, a/b/c.go => c, a/b.c.go => b.c +//!+ +func basename(s string) string { + slash := strings.LastIndex(s, "/") // -1 if "/" not found + s = s[slash+1:] + if dot := strings.LastIndex(s, "."); dot >= 0 { + s = s[:dot] + } + return s +} + +//!- diff --git a/vendor/gopl.io/ch3/comma/main.go b/vendor/gopl.io/ch3/comma/main.go new file mode 100644 index 0000000..6f0f0e9 --- /dev/null +++ b/vendor/gopl.io/ch3/comma/main.go @@ -0,0 +1,40 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 73. + +// Comma prints its argument numbers with a comma at each power of 1000. +// +// Example: +// $ go build gopl.io/ch3/comma +// $ ./comma 1 12 123 1234 1234567890 +// 1 +// 12 +// 123 +// 1,234 +// 1,234,567,890 +// +package main + +import ( + "fmt" + "os" +) + +func main() { + for i := 1; i < len(os.Args); i++ { + fmt.Printf(" %s\n", comma(os.Args[i])) + } +} + +//!+ +// comma inserts commas in a non-negative decimal integer string. +func comma(s string) string { + n := len(s) + if n <= 3 { + return s + } + return comma(s[:n-3]) + "," + s[n-3:] +} + +//!- diff --git a/vendor/gopl.io/ch3/mandelbrot/main.go b/vendor/gopl.io/ch3/mandelbrot/main.go new file mode 100644 index 0000000..805922d --- /dev/null +++ b/vendor/gopl.io/ch3/mandelbrot/main.go @@ -0,0 +1,84 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 61. +//!+ + +// Mandelbrot emits a PNG image of the Mandelbrot fractal. +package main + +import ( + "image" + "image/color" + "image/png" + "math/cmplx" + "os" +) + +func main() { + const ( + xmin, ymin, xmax, ymax = -2, -2, +2, +2 + width, height = 1024, 1024 + ) + + img := image.NewRGBA(image.Rect(0, 0, width, height)) + for py := 0; py < height; py++ { + y := float64(py)/height*(ymax-ymin) + ymin + for px := 0; px < width; px++ { + x := float64(px)/width*(xmax-xmin) + xmin + z := complex(x, y) + // Image point (px, py) represents complex value z. + img.Set(px, py, mandelbrot(z)) + } + } + png.Encode(os.Stdout, img) // NOTE: ignoring errors +} + +func mandelbrot(z complex128) color.Color { + const iterations = 200 + const contrast = 15 + + var v complex128 + for n := uint8(0); n < iterations; n++ { + v = v*v + z + if cmplx.Abs(v) > 2 { + return color.Gray{255 - contrast*n} + } + } + return color.Black +} + +//!- + +// Some other interesting functions: + +func acos(z complex128) color.Color { + v := cmplx.Acos(z) + blue := uint8(real(v)*128) + 127 + red := uint8(imag(v)*128) + 127 + return color.YCbCr{192, blue, red} +} + +func sqrt(z complex128) color.Color { + v := cmplx.Sqrt(z) + blue := uint8(real(v)*128) + 127 + red := uint8(imag(v)*128) + 127 + return color.YCbCr{128, blue, red} +} + +// f(x) = x^4 - 1 +// +// z' = z - f(z)/f'(z) +// = z - (z^4 - 1) / (4 * z^3) +// = z - (z - 1/z^3) / 4 +func newton(z complex128) color.Color { + const iterations = 37 + const contrast = 7 + for i := uint8(0); i < iterations; i++ { + z -= (z - 1/(z*z*z)) / 4 + if cmplx.Abs(z*z*z*z-1) < 1e-6 { + return color.Gray{255 - contrast*i} + } + } + return color.Black +} diff --git a/vendor/gopl.io/ch3/netflag/netflag.go b/vendor/gopl.io/ch3/netflag/netflag.go new file mode 100644 index 0000000..dd4aaff --- /dev/null +++ b/vendor/gopl.io/ch3/netflag/netflag.go @@ -0,0 +1,30 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 77. + +// Netflag demonstrates an integer type used as a bit field. +package main + +import ( + "fmt" + . "net" +) + +//!+ +func IsUp(v Flags) bool { return v&FlagUp == FlagUp } +func TurnDown(v *Flags) { *v &^= FlagUp } +func SetBroadcast(v *Flags) { *v |= FlagBroadcast } +func IsCast(v Flags) bool { return v&(FlagBroadcast|FlagMulticast) != 0 } + +func main() { + var v Flags = FlagMulticast | FlagUp + fmt.Printf("%b %t\n", v, IsUp(v)) // "10001 true" + TurnDown(&v) + fmt.Printf("%b %t\n", v, IsUp(v)) // "10000 false" + SetBroadcast(&v) + fmt.Printf("%b %t\n", v, IsUp(v)) // "10010 false" + fmt.Printf("%b %t\n", v, IsCast(v)) // "10010 true" +} + +//!- diff --git a/vendor/gopl.io/ch3/printints/main.go b/vendor/gopl.io/ch3/printints/main.go new file mode 100644 index 0000000..1c875d8 --- /dev/null +++ b/vendor/gopl.io/ch3/printints/main.go @@ -0,0 +1,33 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 74. + +// Printints demonstrates the use of bytes.Buffer to format a string. +package main + +import ( + "bytes" + "fmt" +) + +//!+ +// intsToString is like fmt.Sprint(values) but adds commas. +func intsToString(values []int) string { + var buf bytes.Buffer + buf.WriteByte('[') + for i, v := range values { + if i > 0 { + buf.WriteString(", ") + } + fmt.Fprintf(&buf, "%d", v) + } + buf.WriteByte(']') + return buf.String() +} + +func main() { + fmt.Println(intsToString([]int{1, 2, 3})) // "[1, 2, 3]" +} + +//!- diff --git a/vendor/gopl.io/ch3/surface/main.go b/vendor/gopl.io/ch3/surface/main.go new file mode 100644 index 0000000..07b26d9 --- /dev/null +++ b/vendor/gopl.io/ch3/surface/main.go @@ -0,0 +1,62 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 58. +//!+ + +// Surface computes an SVG rendering of a 3-D surface function. +package main + +import ( + "fmt" + "math" +) + +const ( + width, height = 600, 320 // canvas size in pixels + cells = 100 // number of grid cells + xyrange = 30.0 // axis ranges (-xyrange..+xyrange) + xyscale = width / 2 / xyrange // pixels per x or y unit + zscale = height * 0.4 // pixels per z unit + angle = math.Pi / 6 // angle of x, y axes (=30°) +) + +var sin30, cos30 = math.Sin(angle), math.Cos(angle) // sin(30°), cos(30°) + +func main() { + fmt.Printf("", width, height) + for i := 0; i < cells; i++ { + for j := 0; j < cells; j++ { + ax, ay := corner(i+1, j) + bx, by := corner(i, j) + cx, cy := corner(i, j+1) + dx, dy := corner(i+1, j+1) + fmt.Printf("\n", + ax, ay, bx, by, cx, cy, dx, dy) + } + } + fmt.Println("") +} + +func corner(i, j int) (float64, float64) { + // Find point (x,y) at corner of cell (i,j). + x := xyrange * (float64(i)/cells - 0.5) + y := xyrange * (float64(j)/cells - 0.5) + + // Compute surface height z. + z := f(x, y) + + // Project (x,y,z) isometrically onto 2-D SVG canvas (sx,sy). + sx := width/2 + (x-y)*cos30*xyscale + sy := height/2 + (x+y)*sin30*xyscale - z*zscale + return sx, sy +} + +func f(x, y float64) float64 { + r := math.Hypot(x, y) // distance from (0,0) + return math.Sin(r) / r +} + +//!- diff --git a/vendor/gopl.io/ch4/append/main.go b/vendor/gopl.io/ch4/append/main.go new file mode 100644 index 0000000..ef95048 --- /dev/null +++ b/vendor/gopl.io/ch4/append/main.go @@ -0,0 +1,79 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 88. + +// Append illustrates the behavior of the built-in append function. +package main + +import "fmt" + +func appendslice(x []int, y ...int) []int { + var z []int + zlen := len(x) + len(y) + if zlen <= cap(x) { + // There is room to expand the slice. + z = x[:zlen] + } else { + // There is insufficient space. + // Grow by doubling, for amortized linear complexity. + zcap := zlen + if zcap < 2*len(x) { + zcap = 2 * len(x) + } + z = make([]int, zlen, zcap) + copy(z, x) + } + copy(z[len(x):], y) + return z +} + +//!+append +func appendInt(x []int, y int) []int { + var z []int + zlen := len(x) + 1 + if zlen <= cap(x) { + // There is room to grow. Extend the slice. + z = x[:zlen] + } else { + // There is insufficient space. Allocate a new array. + // Grow by doubling, for amortized linear complexity. + zcap := zlen + if zcap < 2*len(x) { + zcap = 2 * len(x) + } + z = make([]int, zlen, zcap) + copy(z, x) // a built-in function; see text + } + z[len(x)] = y + return z +} + +//!-append + +//!+growth +func main() { + var x, y []int + for i := 0; i < 10; i++ { + y = appendInt(x, i) + fmt.Printf("%d cap=%d\t%v\n", i, cap(y), y) + x = y + } +} + +//!-growth + +/* +//!+output +0 cap=1 [0] +1 cap=2 [0 1] +2 cap=4 [0 1 2] +3 cap=4 [0 1 2 3] +4 cap=8 [0 1 2 3 4] +5 cap=8 [0 1 2 3 4 5] +6 cap=8 [0 1 2 3 4 5 6] +7 cap=8 [0 1 2 3 4 5 6 7] +8 cap=16 [0 1 2 3 4 5 6 7 8] +9 cap=16 [0 1 2 3 4 5 6 7 8 9] +//!-output +*/ diff --git a/vendor/gopl.io/ch4/autoescape/main.go b/vendor/gopl.io/ch4/autoescape/main.go new file mode 100644 index 0000000..d39e57d --- /dev/null +++ b/vendor/gopl.io/ch4/autoescape/main.go @@ -0,0 +1,30 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 117. + +// Autoescape demonstrates automatic HTML escaping in html/template. +package main + +import ( + "html/template" + "log" + "os" +) + +//!+ +func main() { + const templ = `

A: {{.A}}

B: {{.B}}

` + t := template.Must(template.New("escape").Parse(templ)) + var data struct { + A string // untrusted plain text + B template.HTML // trusted HTML + } + data.A = "Hello!" + data.B = "Hello!" + if err := t.Execute(os.Stdout, data); err != nil { + log.Fatal(err) + } +} + +//!- diff --git a/vendor/gopl.io/ch4/charcount/main.go b/vendor/gopl.io/ch4/charcount/main.go new file mode 100644 index 0000000..ae7a4db --- /dev/null +++ b/vendor/gopl.io/ch4/charcount/main.go @@ -0,0 +1,56 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 97. +//!+ + +// Charcount computes counts of Unicode characters. +package main + +import ( + "bufio" + "fmt" + "io" + "os" + "unicode" + "unicode/utf8" +) + +func main() { + counts := make(map[rune]int) // counts of Unicode characters + var utflen [utf8.UTFMax + 1]int // count of lengths of UTF-8 encodings + invalid := 0 // count of invalid UTF-8 characters + + in := bufio.NewReader(os.Stdin) + for { + r, n, err := in.ReadRune() // returns rune, nbytes, error + if err == io.EOF { + break + } + if err != nil { + fmt.Fprintf(os.Stderr, "charcount: %v\n", err) + os.Exit(1) + } + if r == unicode.ReplacementChar && n == 1 { + invalid++ + continue + } + counts[r]++ + utflen[n]++ + } + fmt.Printf("rune\tcount\n") + for c, n := range counts { + fmt.Printf("%q\t%d\n", c, n) + } + fmt.Print("\nlen\tcount\n") + for i, n := range utflen { + if i > 0 { + fmt.Printf("%d\t%d\n", i, n) + } + } + if invalid > 0 { + fmt.Printf("\n%d invalid UTF-8 characters\n", invalid) + } +} + +//!- diff --git a/vendor/gopl.io/ch4/dedup/main.go b/vendor/gopl.io/ch4/dedup/main.go new file mode 100644 index 0000000..bf32e93 --- /dev/null +++ b/vendor/gopl.io/ch4/dedup/main.go @@ -0,0 +1,33 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 96. + +// Dedup prints only one instance of each line; duplicates are removed. +package main + +import ( + "bufio" + "fmt" + "os" +) + +//!+ +func main() { + seen := make(map[string]bool) // a set of strings + input := bufio.NewScanner(os.Stdin) + for input.Scan() { + line := input.Text() + if !seen[line] { + seen[line] = true + fmt.Println(line) + } + } + + if err := input.Err(); err != nil { + fmt.Fprintf(os.Stderr, "dedup: %v\n", err) + os.Exit(1) + } +} + +//!- diff --git a/vendor/gopl.io/ch4/embed/main.go b/vendor/gopl.io/ch4/embed/main.go new file mode 100644 index 0000000..f85cfcf --- /dev/null +++ b/vendor/gopl.io/ch4/embed/main.go @@ -0,0 +1,46 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 106. + +// Embed demonstrates basic struct embedding. +package main + +import "fmt" + +type Point struct{ X, Y int } + +type Circle struct { + Point + Radius int +} + +type Wheel struct { + Circle + Spokes int +} + +func main() { + var w Wheel + //!+ + w = Wheel{Circle{Point{8, 8}, 5}, 20} + + w = Wheel{ + Circle: Circle{ + Point: Point{X: 8, Y: 8}, + Radius: 5, + }, + Spokes: 20, // NOTE: trailing comma necessary here (and at Radius) + } + + fmt.Printf("%#v\n", w) + // Output: + // Wheel{Circle:Circle{Point:Point{X:8, Y:8}, Radius:5}, Spokes:20} + + w.X = 42 + + fmt.Printf("%#v\n", w) + // Output: + // Wheel{Circle:Circle{Point:Point{X:42, Y:8}, Radius:5}, Spokes:20} + //!- +} diff --git a/vendor/gopl.io/ch4/github/github.go b/vendor/gopl.io/ch4/github/github.go new file mode 100644 index 0000000..053b954 --- /dev/null +++ b/vendor/gopl.io/ch4/github/github.go @@ -0,0 +1,35 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 110. +//!+ + +// Package github provides a Go API for the GitHub issue tracker. +// See https://developer.github.com/v3/search/#search-issues. +package github + +import "time" + +const IssuesURL = "https://api.github.com/search/issues" + +type IssuesSearchResult struct { + TotalCount int `json:"total_count"` + Items []*Issue +} + +type Issue struct { + Number int + HTMLURL string `json:"html_url"` + Title string + State string + User *User + CreatedAt time.Time `json:"created_at"` + Body string // in Markdown format +} + +type User struct { + Login string + HTMLURL string `json:"html_url"` +} + +//!- diff --git a/vendor/gopl.io/ch4/github/search.go b/vendor/gopl.io/ch4/github/search.go new file mode 100644 index 0000000..070666c --- /dev/null +++ b/vendor/gopl.io/ch4/github/search.go @@ -0,0 +1,53 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +//!+ + +package github + +import ( + "encoding/json" + "fmt" + "net/http" + "net/url" + "strings" +) + +// SearchIssues queries the GitHub issue tracker. +func SearchIssues(terms []string) (*IssuesSearchResult, error) { + q := url.QueryEscape(strings.Join(terms, " ")) + resp, err := http.Get(IssuesURL + "?q=" + q) + if err != nil { + return nil, err + } + //!- + // For long-term stability, instead of http.Get, use the + // variant below which adds an HTTP request header indicating + // that only version 3 of the GitHub API is acceptable. + // + // req, err := http.NewRequest("GET", IssuesURL+"?q="+q, nil) + // if err != nil { + // return nil, err + // } + // req.Header.Set( + // "Accept", "application/vnd.github.v3.text-match+json") + // resp, err := http.DefaultClient.Do(req) + //!+ + + // We must close resp.Body on all execution paths. + // (Chapter 5 presents 'defer', which makes this simpler.) + if resp.StatusCode != http.StatusOK { + resp.Body.Close() + return nil, fmt.Errorf("search query failed: %s", resp.Status) + } + + var result IssuesSearchResult + if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { + resp.Body.Close() + return nil, err + } + resp.Body.Close() + return &result, nil +} + +//!- diff --git a/vendor/gopl.io/ch4/graph/main.go b/vendor/gopl.io/ch4/graph/main.go new file mode 100644 index 0000000..e47d90c --- /dev/null +++ b/vendor/gopl.io/ch4/graph/main.go @@ -0,0 +1,43 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 99. + +// Graph shows how to use a map of maps to represent a directed graph. +package main + +import "fmt" + +//!+ +var graph = make(map[string]map[string]bool) + +func addEdge(from, to string) { + edges := graph[from] + if edges == nil { + edges = make(map[string]bool) + graph[from] = edges + } + edges[to] = true +} + +func hasEdge(from, to string) bool { + return graph[from][to] +} + +//!- + +func main() { + addEdge("a", "b") + addEdge("c", "d") + addEdge("a", "d") + addEdge("d", "a") + fmt.Println(hasEdge("a", "b")) + fmt.Println(hasEdge("c", "d")) + fmt.Println(hasEdge("a", "d")) + fmt.Println(hasEdge("d", "a")) + fmt.Println(hasEdge("x", "b")) + fmt.Println(hasEdge("c", "d")) + fmt.Println(hasEdge("x", "d")) + fmt.Println(hasEdge("d", "x")) + +} diff --git a/vendor/gopl.io/ch4/issues/main.go b/vendor/gopl.io/ch4/issues/main.go new file mode 100644 index 0000000..b1b6dbf --- /dev/null +++ b/vendor/gopl.io/ch4/issues/main.go @@ -0,0 +1,52 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 112. +//!+ + +// Issues prints a table of GitHub issues matching the search terms. +package main + +import ( + "fmt" + "log" + "os" + + "gopl.io/ch4/github" +) + +//!+ +func main() { + result, err := github.SearchIssues(os.Args[1:]) + if err != nil { + log.Fatal(err) + } + fmt.Printf("%d issues:\n", result.TotalCount) + for _, item := range result.Items { + fmt.Printf("#%-5d %9.9s %.55s\n", + item.Number, item.User.Login, item.Title) + } +} + +//!- + +/* +//!+textoutput +$ go build gopl.io/ch4/issues +$ ./issues repo:golang/go is:open json decoder +13 issues: +#5680 eaigner encoding/json: set key converter on en/decoder +#6050 gopherbot encoding/json: provide tokenizer +#8658 gopherbot encoding/json: use bufio +#8462 kortschak encoding/json: UnmarshalText confuses json.Unmarshal +#5901 rsc encoding/json: allow override type marshaling +#9812 klauspost encoding/json: string tag not symmetric +#7872 extempora encoding/json: Encoder internally buffers full output +#9650 cespare encoding/json: Decoding gives errPhase when unmarshalin +#6716 gopherbot encoding/json: include field name in unmarshal error me +#6901 lukescott encoding/json, encoding/xml: option to treat unknown fi +#6384 joeshaw encoding/json: encode precise floating point integers u +#6647 btracey x/tools/cmd/godoc: display type kind of each named type +#4237 gjemiller encoding/base64: URLEncoding padding is optional +//!-textoutput +*/ diff --git a/vendor/gopl.io/ch4/issueshtml/main.go b/vendor/gopl.io/ch4/issueshtml/main.go new file mode 100644 index 0000000..9e2c36d --- /dev/null +++ b/vendor/gopl.io/ch4/issueshtml/main.go @@ -0,0 +1,52 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 115. + +// Issueshtml prints an HTML table of issues matching the search terms. +package main + +import ( + "log" + "os" + + "gopl.io/ch4/github" +) + +//!+template +import "html/template" + +var issueList = template.Must(template.New("issuelist").Parse(` +

{{.TotalCount}} issues

+ + + + + + + +{{range .Items}} + + + + + + +{{end}} +
#StateUserTitle
{{.Number}}{{.State}}{{.User.Login}}{{.Title}}
+`)) + +//!-template + +//!+ +func main() { + result, err := github.SearchIssues(os.Args[1:]) + if err != nil { + log.Fatal(err) + } + if err := issueList.Execute(os.Stdout, result); err != nil { + log.Fatal(err) + } +} + +//!- diff --git a/vendor/gopl.io/ch4/issuesreport/main.go b/vendor/gopl.io/ch4/issuesreport/main.go new file mode 100644 index 0000000..2d41afd --- /dev/null +++ b/vendor/gopl.io/ch4/issuesreport/main.go @@ -0,0 +1,89 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 113. + +// Issuesreport prints a report of issues matching the search terms. +package main + +import ( + "log" + "os" + "text/template" + "time" + + "gopl.io/ch4/github" +) + +//!+template +const templ = `{{.TotalCount}} issues: +{{range .Items}}---------------------------------------- +Number: {{.Number}} +User: {{.User.Login}} +Title: {{.Title | printf "%.64s"}} +Age: {{.CreatedAt | daysAgo}} days +{{end}}` + +//!-template + +//!+daysAgo +func daysAgo(t time.Time) int { + return int(time.Since(t).Hours() / 24) +} + +//!-daysAgo + +//!+exec +var report = template.Must(template.New("issuelist"). + Funcs(template.FuncMap{"daysAgo": daysAgo}). + Parse(templ)) + +func main() { + result, err := github.SearchIssues(os.Args[1:]) + if err != nil { + log.Fatal(err) + } + if err := report.Execute(os.Stdout, result); err != nil { + log.Fatal(err) + } +} + +//!-exec + +func noMust() { + //!+parse + report, err := template.New("report"). + Funcs(template.FuncMap{"daysAgo": daysAgo}). + Parse(templ) + if err != nil { + log.Fatal(err) + } + //!-parse + result, err := github.SearchIssues(os.Args[1:]) + if err != nil { + log.Fatal(err) + } + if err := report.Execute(os.Stdout, result); err != nil { + log.Fatal(err) + } +} + +/* +//!+output +$ go build gopl.io/ch4/issuesreport +$ ./issuesreport repo:golang/go is:open json decoder +13 issues: +---------------------------------------- +Number: 5680 +User: eaigner +Title: encoding/json: set key converter on en/decoder +Age: 750 days +---------------------------------------- +Number: 6050 +User: gopherbot +Title: encoding/json: provide tokenizer +Age: 695 days +---------------------------------------- +... +//!-output +*/ diff --git a/vendor/gopl.io/ch4/movie/main.go b/vendor/gopl.io/ch4/movie/main.go new file mode 100644 index 0000000..6429410 --- /dev/null +++ b/vendor/gopl.io/ch4/movie/main.go @@ -0,0 +1,104 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 108. + +// Movie prints Movies as JSON. +package main + +import ( + "encoding/json" + "fmt" + "log" +) + +//!+ +type Movie struct { + Title string + Year int `json:"released"` + Color bool `json:"color,omitempty"` + Actors []string +} + +var movies = []Movie{ + {Title: "Casablanca", Year: 1942, Color: false, + Actors: []string{"Humphrey Bogart", "Ingrid Bergman"}}, + {Title: "Cool Hand Luke", Year: 1967, Color: true, + Actors: []string{"Paul Newman"}}, + {Title: "Bullitt", Year: 1968, Color: true, + Actors: []string{"Steve McQueen", "Jacqueline Bisset"}}, + // ... +} + +//!- + +func main() { + { + //!+Marshal + data, err := json.Marshal(movies) + if err != nil { + log.Fatalf("JSON marshaling failed: %s", err) + } + fmt.Printf("%s\n", data) + //!-Marshal + } + + { + //!+MarshalIndent + data, err := json.MarshalIndent(movies, "", " ") + if err != nil { + log.Fatalf("JSON marshaling failed: %s", err) + } + fmt.Printf("%s\n", data) + //!-MarshalIndent + + //!+Unmarshal + var titles []struct{ Title string } + if err := json.Unmarshal(data, &titles); err != nil { + log.Fatalf("JSON unmarshaling failed: %s", err) + } + fmt.Println(titles) // "[{Casablanca} {Cool Hand Luke} {Bullitt}]" + //!-Unmarshal + } +} + +/* +//!+output +[{"Title":"Casablanca","released":1942,"Actors":["Humphrey Bogart","Ingr +id Bergman"]},{"Title":"Cool Hand Luke","released":1967,"color":true,"Ac +tors":["Paul Newman"]},{"Title":"Bullitt","released":1968,"color":true," +Actors":["Steve McQueen","Jacqueline Bisset"]}] +//!-output +*/ + +/* +//!+indented +[ + { + "Title": "Casablanca", + "released": 1942, + "Actors": [ + "Humphrey Bogart", + "Ingrid Bergman" + ] + }, + { + "Title": "Cool Hand Luke", + "released": 1967, + "color": true, + "Actors": [ + "Paul Newman" + ] + }, + { + "Title": "Bullitt", + "released": 1968, + "color": true, + "Actors": [ + "Steve McQueen", + "Jacqueline Bisset" + ] + } +] +//!-indented +*/ diff --git a/vendor/gopl.io/ch4/nonempty/main.go b/vendor/gopl.io/ch4/nonempty/main.go new file mode 100644 index 0000000..2a20c84 --- /dev/null +++ b/vendor/gopl.io/ch4/nonempty/main.go @@ -0,0 +1,47 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 91. + +//!+nonempty + +// Nonempty is an example of an in-place slice algorithm. +package main + +import "fmt" + +// nonempty returns a slice holding only the non-empty strings. +// The underlying array is modified during the call. +func nonempty(strings []string) []string { + i := 0 + for _, s := range strings { + if s != "" { + strings[i] = s + i++ + } + } + return strings[:i] +} + +//!-nonempty + +func main() { + //!+main + data := []string{"one", "", "three"} + fmt.Printf("%q\n", nonempty(data)) // `["one" "three"]` + fmt.Printf("%q\n", data) // `["one" "three" "three"]` + //!-main +} + +//!+alt +func nonempty2(strings []string) []string { + out := strings[:0] // zero-length slice of original + for _, s := range strings { + if s != "" { + out = append(out, s) + } + } + return out +} + +//!-alt diff --git a/vendor/gopl.io/ch4/rev/main.go b/vendor/gopl.io/ch4/rev/main.go new file mode 100644 index 0000000..039b58a --- /dev/null +++ b/vendor/gopl.io/ch4/rev/main.go @@ -0,0 +1,60 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 86. + +// Rev reverses a slice. +package main + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" +) + +func main() { + //!+array + a := [...]int{0, 1, 2, 3, 4, 5} + reverse(a[:]) + fmt.Println(a) // "[5 4 3 2 1 0]" + //!-array + + //!+slice + s := []int{0, 1, 2, 3, 4, 5} + // Rotate s left by two positions. + reverse(s[:2]) + reverse(s[2:]) + reverse(s) + fmt.Println(s) // "[2 3 4 5 0 1]" + //!-slice + + // Interactive test of reverse. + input := bufio.NewScanner(os.Stdin) +outer: + for input.Scan() { + var ints []int + for _, s := range strings.Fields(input.Text()) { + x, err := strconv.ParseInt(s, 10, 64) + if err != nil { + fmt.Fprintln(os.Stderr, err) + continue outer + } + ints = append(ints, int(x)) + } + reverse(ints) + fmt.Printf("%v\n", ints) + } + // NOTE: ignoring potential errors from input.Err() +} + +//!+rev +// reverse reverses a slice of ints in place. +func reverse(s []int) { + for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { + s[i], s[j] = s[j], s[i] + } +} + +//!-rev diff --git a/vendor/gopl.io/ch4/sha256/main.go b/vendor/gopl.io/ch4/sha256/main.go new file mode 100644 index 0000000..51e7b24 --- /dev/null +++ b/vendor/gopl.io/ch4/sha256/main.go @@ -0,0 +1,25 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 83. + +// The sha256 command computes the SHA256 hash (an array) of a string. +package main + +import "fmt" + +//!+ +import "crypto/sha256" + +func main() { + c1 := sha256.Sum256([]byte("x")) + c2 := sha256.Sum256([]byte("X")) + fmt.Printf("%x\n%x\n%t\n%T\n", c1, c2, c1 == c2, c1) + // Output: + // 2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881 + // 4b68ab3847feda7d6c62c1fbcbeebfa35eab7351ed5e78f4ddadea5df64b8015 + // false + // [32]uint8 +} + +//!- diff --git a/vendor/gopl.io/ch4/treesort/sort.go b/vendor/gopl.io/ch4/treesort/sort.go new file mode 100644 index 0000000..f9ee575 --- /dev/null +++ b/vendor/gopl.io/ch4/treesort/sort.go @@ -0,0 +1,50 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 101. + +// Package treesort provides insertion sort using an unbalanced binary tree. +package treesort + +//!+ +type tree struct { + value int + left, right *tree +} + +// Sort sorts values in place. +func Sort(values []int) { + var root *tree + for _, v := range values { + root = add(root, v) + } + appendValues(values[:0], root) +} + +// appendValues appends the elements of t to values in order +// and returns the resulting slice. +func appendValues(values []int, t *tree) []int { + if t != nil { + values = appendValues(values, t.left) + values = append(values, t.value) + values = appendValues(values, t.right) + } + return values +} + +func add(t *tree, value int) *tree { + if t == nil { + // Equivalent to return &tree{value: value}. + t = new(tree) + t.value = value + return t + } + if value < t.value { + t.left = add(t.left, value) + } else { + t.right = add(t.right, value) + } + return t +} + +//!- diff --git a/vendor/gopl.io/ch4/treesort/sort_test.go b/vendor/gopl.io/ch4/treesort/sort_test.go new file mode 100644 index 0000000..bf0cb02 --- /dev/null +++ b/vendor/gopl.io/ch4/treesort/sort_test.go @@ -0,0 +1,23 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package treesort_test + +import ( + "math/rand" + "sort" + "testing" + + "gopl.io/ch4/treesort" +) + +func TestSort(t *testing.T) { + data := make([]int, 50) + for i := range data { + data[i] = rand.Int() % 50 + } + treesort.Sort(data) + if !sort.IntsAreSorted(data) { + t.Errorf("not sorted: %v", data) + } +} diff --git a/vendor/gopl.io/ch5/defer1/defer.go b/vendor/gopl.io/ch5/defer1/defer.go new file mode 100644 index 0000000..3d2b80e --- /dev/null +++ b/vendor/gopl.io/ch5/defer1/defer.go @@ -0,0 +1,48 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 150. + +// Defer1 demonstrates a deferred call being invoked during a panic. +package main + +import "fmt" + +//!+f +func main() { + f(3) +} + +func f(x int) { + fmt.Printf("f(%d)\n", x+0/x) // panics if x == 0 + defer fmt.Printf("defer %d\n", x) + f(x - 1) +} + +//!-f + +/* +//!+stdout +f(3) +f(2) +f(1) +defer 1 +defer 2 +defer 3 +//!-stdout + +//!+stderr +panic: runtime error: integer divide by zero +main.f(0) + src/gopl.io/ch5/defer1/defer.go:14 +main.f(1) + src/gopl.io/ch5/defer1/defer.go:16 +main.f(2) + src/gopl.io/ch5/defer1/defer.go:16 + +main.f(3) + src/gopl.io/ch5/defer1/defer.go:16 +main.main() + src/gopl.io/ch5/defer1/defer.go:10 +//!-stderr +*/ diff --git a/vendor/gopl.io/ch5/defer2/defer.go b/vendor/gopl.io/ch5/defer2/defer.go new file mode 100644 index 0000000..25fa881 --- /dev/null +++ b/vendor/gopl.io/ch5/defer2/defer.go @@ -0,0 +1,51 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 151. + +// Defer2 demonstrates a deferred call to runtime.Stack during a panic. +package main + +import ( + "fmt" + "os" + "runtime" +) + +//!+ +func main() { + defer printStack() + f(3) +} + +func printStack() { + var buf [4096]byte + n := runtime.Stack(buf[:], false) + os.Stdout.Write(buf[:n]) +} + +//!- + +func f(x int) { + fmt.Printf("f(%d)\n", x+0/x) // panics if x == 0 + defer fmt.Printf("defer %d\n", x) + f(x - 1) +} + +/* +//!+printstack +goroutine 1 [running]: +main.printStack() + src/gopl.io/ch5/defer2/defer.go:20 +main.f(0) + src/gopl.io/ch5/defer2/defer.go:27 +main.f(1) + src/gopl.io/ch5/defer2/defer.go:29 +main.f(2) + src/gopl.io/ch5/defer2/defer.go:29 +main.f(3) + src/gopl.io/ch5/defer2/defer.go:29 +main.main() + src/gopl.io/ch5/defer2/defer.go:15 +//!-printstack +*/ diff --git a/vendor/gopl.io/ch5/fetch/main.go b/vendor/gopl.io/ch5/fetch/main.go new file mode 100644 index 0000000..c838195 --- /dev/null +++ b/vendor/gopl.io/ch5/fetch/main.go @@ -0,0 +1,54 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 148. + +// Fetch saves the contents of a URL into a local file. +package main + +import ( + "fmt" + "io" + "net/http" + "os" + "path" +) + +//!+ +// Fetch downloads the URL and returns the +// name and length of the local file. +func fetch(url string) (filename string, n int64, err error) { + resp, err := http.Get(url) + if err != nil { + return "", 0, err + } + defer resp.Body.Close() + + local := path.Base(resp.Request.URL.Path) + if local == "/" { + local = "index.html" + } + f, err := os.Create(local) + if err != nil { + return "", 0, err + } + n, err = io.Copy(f, resp.Body) + // Close file, but prefer error from Copy, if any. + if closeErr := f.Close(); err == nil { + err = closeErr + } + return local, n, err +} + +//!- + +func main() { + for _, url := range os.Args[1:] { + local, n, err := fetch(url) + if err != nil { + fmt.Fprintf(os.Stderr, "fetch %s: %v\n", url, err) + continue + } + fmt.Fprintf(os.Stderr, "%s => %s (%d bytes).\n", url, local, n) + } +} diff --git a/vendor/gopl.io/ch5/findlinks1/main.go b/vendor/gopl.io/ch5/findlinks1/main.go new file mode 100644 index 0000000..8996671 --- /dev/null +++ b/vendor/gopl.io/ch5/findlinks1/main.go @@ -0,0 +1,76 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 122. +//!+main + +// Findlinks1 prints the links in an HTML document read from standard input. +package main + +import ( + "fmt" + "os" + + "golang.org/x/net/html" +) + +func main() { + doc, err := html.Parse(os.Stdin) + if err != nil { + fmt.Fprintf(os.Stderr, "findlinks1: %v\n", err) + os.Exit(1) + } + for _, link := range visit(nil, doc) { + fmt.Println(link) + } +} + +//!-main + +//!+visit +// visit appends to links each link found in n and returns the result. +func visit(links []string, n *html.Node) []string { + if n.Type == html.ElementNode && n.Data == "a" { + for _, a := range n.Attr { + if a.Key == "href" { + links = append(links, a.Val) + } + } + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + links = visit(links, c) + } + return links +} + +//!-visit + +/* +//!+html +package html + +type Node struct { + Type NodeType + Data string + Attr []Attribute + FirstChild, NextSibling *Node +} + +type NodeType int32 + +const ( + ErrorNode NodeType = iota + TextNode + DocumentNode + ElementNode + CommentNode + DoctypeNode +) + +type Attribute struct { + Key, Val string +} + +func Parse(r io.Reader) (*Node, error) +//!-html +*/ diff --git a/vendor/gopl.io/ch5/findlinks2/main.go b/vendor/gopl.io/ch5/findlinks2/main.go new file mode 100644 index 0000000..35ba2a5 --- /dev/null +++ b/vendor/gopl.io/ch5/findlinks2/main.go @@ -0,0 +1,69 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 125. + +// Findlinks2 does an HTTP GET on each URL, parses the +// result as HTML, and prints the links within it. +// +// Usage: +// findlinks url ... +package main + +import ( + "fmt" + "net/http" + "os" + + "golang.org/x/net/html" +) + +// visit appends to links each link found in n, and returns the result. +func visit(links []string, n *html.Node) []string { + if n.Type == html.ElementNode && n.Data == "a" { + for _, a := range n.Attr { + if a.Key == "href" { + links = append(links, a.Val) + } + } + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + links = visit(links, c) + } + return links +} + +//!+ +func main() { + for _, url := range os.Args[1:] { + links, err := findLinks(url) + if err != nil { + fmt.Fprintf(os.Stderr, "findlinks2: %v\n", err) + continue + } + for _, link := range links { + fmt.Println(link) + } + } +} + +// findLinks performs an HTTP GET request for url, parses the +// response as HTML, and extracts and returns the links. +func findLinks(url string) ([]string, error) { + resp, err := http.Get(url) + if err != nil { + return nil, err + } + if resp.StatusCode != http.StatusOK { + resp.Body.Close() + return nil, fmt.Errorf("getting %s: %s", url, resp.Status) + } + doc, err := html.Parse(resp.Body) + resp.Body.Close() + if err != nil { + return nil, fmt.Errorf("parsing %s as HTML: %v", url, err) + } + return visit(nil, doc), nil +} + +//!- diff --git a/vendor/gopl.io/ch5/findlinks3/findlinks.go b/vendor/gopl.io/ch5/findlinks3/findlinks.go new file mode 100644 index 0000000..f45b39e --- /dev/null +++ b/vendor/gopl.io/ch5/findlinks3/findlinks.go @@ -0,0 +1,56 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 139. + +// Findlinks3 crawls the web, starting with the URLs on the command line. +package main + +import ( + "fmt" + "log" + "os" + + "gopl.io/ch5/links" +) + +//!+breadthFirst +// breadthFirst calls f for each item in the worklist. +// Any items returned by f are added to the worklist. +// f is called at most once for each item. +func breadthFirst(f func(item string) []string, worklist []string) { + seen := make(map[string]bool) + for len(worklist) > 0 { + items := worklist + worklist = nil + for _, item := range items { + if !seen[item] { + seen[item] = true + worklist = append(worklist, f(item)...) + } + } + } +} + +//!-breadthFirst + +//!+crawl +func crawl(url string) []string { + fmt.Println(url) + list, err := links.Extract(url) + if err != nil { + log.Print(err) + } + return list +} + +//!-crawl + +//!+main +func main() { + // Crawl the web breadth-first, + // starting from the command-line arguments. + breadthFirst(crawl, os.Args[1:]) +} + +//!-main diff --git a/vendor/gopl.io/ch5/links/links.go b/vendor/gopl.io/ch5/links/links.go new file mode 100644 index 0000000..2df9e14 --- /dev/null +++ b/vendor/gopl.io/ch5/links/links.go @@ -0,0 +1,67 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 138. +//!+Extract + +// Package links provides a link-extraction function. +package links + +import ( + "fmt" + "net/http" + + "golang.org/x/net/html" +) + +// Extract makes an HTTP GET request to the specified URL, parses +// the response as HTML, and returns the links in the HTML document. +func Extract(url string) ([]string, error) { + resp, err := http.Get(url) + if err != nil { + return nil, err + } + if resp.StatusCode != http.StatusOK { + resp.Body.Close() + return nil, fmt.Errorf("getting %s: %s", url, resp.Status) + } + + doc, err := html.Parse(resp.Body) + resp.Body.Close() + if err != nil { + return nil, fmt.Errorf("parsing %s as HTML: %v", url, err) + } + + var links []string + visitNode := func(n *html.Node) { + if n.Type == html.ElementNode && n.Data == "a" { + for _, a := range n.Attr { + if a.Key != "href" { + continue + } + link, err := resp.Request.URL.Parse(a.Val) + if err != nil { + continue // ignore bad URLs + } + links = append(links, link.String()) + } + } + } + forEachNode(doc, visitNode, nil) + return links, nil +} + +//!-Extract + +// Copied from gopl.io/ch5/outline2. +func forEachNode(n *html.Node, pre, post func(n *html.Node)) { + if pre != nil { + pre(n) + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + forEachNode(c, pre, post) + } + if post != nil { + post(n) + } +} diff --git a/vendor/gopl.io/ch5/outline/main.go b/vendor/gopl.io/ch5/outline/main.go new file mode 100644 index 0000000..d3ccbf9 --- /dev/null +++ b/vendor/gopl.io/ch5/outline/main.go @@ -0,0 +1,36 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 123. + +// Outline prints the outline of an HTML document tree. +package main + +import ( + "fmt" + "os" + + "golang.org/x/net/html" +) + +//!+ +func main() { + doc, err := html.Parse(os.Stdin) + if err != nil { + fmt.Fprintf(os.Stderr, "outline: %v\n", err) + os.Exit(1) + } + outline(nil, doc) +} + +func outline(stack []string, n *html.Node) { + if n.Type == html.ElementNode { + stack = append(stack, n.Data) // push tag + fmt.Println(stack) + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + outline(stack, c) + } +} + +//!- diff --git a/vendor/gopl.io/ch5/outline2/outline.go b/vendor/gopl.io/ch5/outline2/outline.go new file mode 100644 index 0000000..d3aee13 --- /dev/null +++ b/vendor/gopl.io/ch5/outline2/outline.go @@ -0,0 +1,80 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 133. + +// Outline prints the outline of an HTML document tree. +package main + +import ( + "fmt" + "net/http" + "os" + + "golang.org/x/net/html" +) + +func main() { + for _, url := range os.Args[1:] { + outline(url) + } +} + +func outline(url string) error { + resp, err := http.Get(url) + if err != nil { + return err + } + defer resp.Body.Close() + + doc, err := html.Parse(resp.Body) + if err != nil { + return err + } + + //!+call + forEachNode(doc, startElement, endElement) + //!-call + + return nil +} + +//!+forEachNode +// forEachNode calls the functions pre(x) and post(x) for each node +// x in the tree rooted at n. Both functions are optional. +// pre is called before the children are visited (preorder) and +// post is called after (postorder). +func forEachNode(n *html.Node, pre, post func(n *html.Node)) { + if pre != nil { + pre(n) + } + + for c := n.FirstChild; c != nil; c = c.NextSibling { + forEachNode(c, pre, post) + } + + if post != nil { + post(n) + } +} + +//!-forEachNode + +//!+startend +var depth int + +func startElement(n *html.Node) { + if n.Type == html.ElementNode { + fmt.Printf("%*s<%s>\n", depth*2, "", n.Data) + depth++ + } +} + +func endElement(n *html.Node) { + if n.Type == html.ElementNode { + depth-- + fmt.Printf("%*s\n", depth*2, "", n.Data) + } +} + +//!-startend diff --git a/vendor/gopl.io/ch5/squares/main.go b/vendor/gopl.io/ch5/squares/main.go new file mode 100644 index 0000000..1e10060 --- /dev/null +++ b/vendor/gopl.io/ch5/squares/main.go @@ -0,0 +1,30 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 135. + +// The squares program demonstrates a function value with state. +package main + +import "fmt" + +//!+ +// squares returns a function that returns +// the next square number each time it is called. +func squares() func() int { + var x int + return func() int { + x++ + return x * x + } +} + +func main() { + f := squares() + fmt.Println(f()) // "1" + fmt.Println(f()) // "4" + fmt.Println(f()) // "9" + fmt.Println(f()) // "16" +} + +//!- diff --git a/vendor/gopl.io/ch5/sum/main.go b/vendor/gopl.io/ch5/sum/main.go new file mode 100644 index 0000000..0a60d35 --- /dev/null +++ b/vendor/gopl.io/ch5/sum/main.go @@ -0,0 +1,33 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 142. + +// The sum program demonstrates a variadic function. +package main + +import "fmt" + +//!+ +func sum(vals ...int) int { + total := 0 + for _, val := range vals { + total += val + } + return total +} + +//!- + +func main() { + //!+main + fmt.Println(sum()) // "0" + fmt.Println(sum(3)) // "3" + fmt.Println(sum(1, 2, 3, 4)) // "10" + //!-main + + //!+slice + values := []int{1, 2, 3, 4} + fmt.Println(sum(values...)) // "10" + //!-slice +} diff --git a/vendor/gopl.io/ch5/title1/title.go b/vendor/gopl.io/ch5/title1/title.go new file mode 100644 index 0000000..65b5276 --- /dev/null +++ b/vendor/gopl.io/ch5/title1/title.go @@ -0,0 +1,82 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 144. + +// Title1 prints the title of an HTML document specified by a URL. +package main + +/* +//!+output +$ go build gopl.io/ch5/title1 +$ ./title1 http://gopl.io +The Go Programming Language +$ ./title1 https://golang.org/doc/effective_go.html +Effective Go - The Go Programming Language +$ ./title1 https://golang.org/doc/gopher/frontpage.png +title: https://golang.org/doc/gopher/frontpage.png + has type image/png, not text/html +//!-output +*/ + +import ( + "fmt" + "net/http" + "os" + "strings" + + "golang.org/x/net/html" +) + +// Copied from gopl.io/ch5/outline2. +func forEachNode(n *html.Node, pre, post func(n *html.Node)) { + if pre != nil { + pre(n) + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + forEachNode(c, pre, post) + } + if post != nil { + post(n) + } +} + +//!+ +func title(url string) error { + resp, err := http.Get(url) + if err != nil { + return err + } + + // Check Content-Type is HTML (e.g., "text/html; charset=utf-8"). + ct := resp.Header.Get("Content-Type") + if ct != "text/html" && !strings.HasPrefix(ct, "text/html;") { + resp.Body.Close() + return fmt.Errorf("%s has type %s, not text/html", url, ct) + } + + doc, err := html.Parse(resp.Body) + resp.Body.Close() + if err != nil { + return fmt.Errorf("parsing %s as HTML: %v", url, err) + } + + visitNode := func(n *html.Node) { + if n.Type == html.ElementNode && n.Data == "title" && + n.FirstChild != nil { + fmt.Println(n.FirstChild.Data) + } + } + forEachNode(doc, visitNode, nil) + return nil +} + +//!- + +func main() { + for _, arg := range os.Args[1:] { + if err := title(arg); err != nil { + fmt.Fprintf(os.Stderr, "title: %v\n", err) + } + } +} diff --git a/vendor/gopl.io/ch5/title2/title.go b/vendor/gopl.io/ch5/title2/title.go new file mode 100644 index 0000000..1641739 --- /dev/null +++ b/vendor/gopl.io/ch5/title2/title.go @@ -0,0 +1,72 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 145. + +// Title2 prints the title of an HTML document specified by a URL. +// It uses defer to simplify closing the response body stream. +package main + +import ( + "fmt" + "net/http" + "os" + "strings" + + "golang.org/x/net/html" +) + +// Copied from gopl.io/ch5/outline2. +func forEachNode(n *html.Node, pre, post func(n *html.Node)) { + if pre != nil { + pre(n) + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + forEachNode(c, pre, post) + } + if post != nil { + post(n) + } +} + +//!+ +func title(url string) error { + resp, err := http.Get(url) + if err != nil { + return err + } + defer resp.Body.Close() + + ct := resp.Header.Get("Content-Type") + if ct != "text/html" && !strings.HasPrefix(ct, "text/html;") { + return fmt.Errorf("%s has type %s, not text/html", url, ct) + } + + doc, err := html.Parse(resp.Body) + if err != nil { + return fmt.Errorf("parsing %s as HTML: %v", url, err) + } + + // ...print doc's title element... + //!- + visitNode := func(n *html.Node) { + if n.Type == html.ElementNode && n.Data == "title" && + n.FirstChild != nil { + fmt.Println(n.FirstChild.Data) + } + } + forEachNode(doc, visitNode, nil) + //!+ + + return nil +} + +//!- + +func main() { + for _, arg := range os.Args[1:] { + if err := title(arg); err != nil { + fmt.Fprintf(os.Stderr, "title: %v\n", err) + } + } +} diff --git a/vendor/gopl.io/ch5/title3/title.go b/vendor/gopl.io/ch5/title3/title.go new file mode 100644 index 0000000..727b209 --- /dev/null +++ b/vendor/gopl.io/ch5/title3/title.go @@ -0,0 +1,99 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 153. + +// Title3 prints the title of an HTML document specified by a URL. +package main + +import ( + "fmt" + "net/http" + "os" + "strings" + + "golang.org/x/net/html" +) + +// Copied from gopl.io/ch5/outline2. +func forEachNode(n *html.Node, pre, post func(n *html.Node)) { + if pre != nil { + pre(n) + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + forEachNode(c, pre, post) + } + if post != nil { + post(n) + } +} + +//!+ +// soleTitle returns the text of the first non-empty title element +// in doc, and an error if there was not exactly one. +func soleTitle(doc *html.Node) (title string, err error) { + type bailout struct{} + + defer func() { + switch p := recover(); p { + case nil: + // no panic + case bailout{}: + // "expected" panic + err = fmt.Errorf("multiple title elements") + default: + panic(p) // unexpected panic; carry on panicking + } + }() + + // Bail out of recursion if we find more than one non-empty title. + forEachNode(doc, func(n *html.Node) { + if n.Type == html.ElementNode && n.Data == "title" && + n.FirstChild != nil { + if title != "" { + panic(bailout{}) // multiple title elements + } + title = n.FirstChild.Data + } + }, nil) + if title == "" { + return "", fmt.Errorf("no title element") + } + return title, nil +} + +//!- + +func title(url string) error { + resp, err := http.Get(url) + if err != nil { + return err + } + + // Check Content-Type is HTML (e.g., "text/html; charset=utf-8"). + ct := resp.Header.Get("Content-Type") + if ct != "text/html" && !strings.HasPrefix(ct, "text/html;") { + resp.Body.Close() + return fmt.Errorf("%s has type %s, not text/html", url, ct) + } + + doc, err := html.Parse(resp.Body) + resp.Body.Close() + if err != nil { + return fmt.Errorf("parsing %s as HTML: %v", url, err) + } + title, err := soleTitle(doc) + if err != nil { + return err + } + fmt.Println(title) + return nil +} + +func main() { + for _, arg := range os.Args[1:] { + if err := title(arg); err != nil { + fmt.Fprintf(os.Stderr, "title: %v\n", err) + } + } +} diff --git a/vendor/gopl.io/ch5/toposort/main.go b/vendor/gopl.io/ch5/toposort/main.go new file mode 100644 index 0000000..1c5e899 --- /dev/null +++ b/vendor/gopl.io/ch5/toposort/main.go @@ -0,0 +1,69 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 136. + +// The toposort program prints the nodes of a DAG in topological order. +package main + +import ( + "fmt" + "sort" +) + +//!+table +// prereqs maps computer science courses to their prerequisites. +var prereqs = map[string][]string{ + "algorithms": {"data structures"}, + "calculus": {"linear algebra"}, + + "compilers": { + "data structures", + "formal languages", + "computer organization", + }, + + "data structures": {"discrete math"}, + "databases": {"data structures"}, + "discrete math": {"intro to programming"}, + "formal languages": {"discrete math"}, + "networks": {"operating systems"}, + "operating systems": {"data structures", "computer organization"}, + "programming languages": {"data structures", "computer organization"}, +} + +//!-table + +//!+main +func main() { + for i, course := range topoSort(prereqs) { + fmt.Printf("%d:\t%s\n", i+1, course) + } +} + +func topoSort(m map[string][]string) []string { + var order []string + seen := make(map[string]bool) + var visitAll func(items []string) + + visitAll = func(items []string) { + for _, item := range items { + if !seen[item] { + seen[item] = true + visitAll(m[item]) + order = append(order, item) + } + } + } + + var keys []string + for key := range m { + keys = append(keys, key) + } + + sort.Strings(keys) + visitAll(keys) + return order +} + +//!-main diff --git a/vendor/gopl.io/ch5/trace/main.go b/vendor/gopl.io/ch5/trace/main.go new file mode 100644 index 0000000..cc1962f --- /dev/null +++ b/vendor/gopl.io/ch5/trace/main.go @@ -0,0 +1,40 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 146. + +// The trace program uses defer to add entry/exit diagnostics to a function. +package main + +import ( + "log" + "time" +) + +//!+main +func bigSlowOperation() { + defer trace("bigSlowOperation")() // don't forget the extra parentheses + // ...lots of work... + time.Sleep(10 * time.Second) // simulate slow operation by sleeping +} + +func trace(msg string) func() { + start := time.Now() + log.Printf("enter %s", msg) + return func() { log.Printf("exit %s (%s)", msg, time.Since(start)) } +} + +//!-main + +func main() { + bigSlowOperation() +} + +/* +!+output +$ go build gopl.io/ch5/trace +$ ./trace +2015/11/18 09:53:26 enter bigSlowOperation +2015/11/18 09:53:36 exit bigSlowOperation (10.000589217s) +!-output +*/ diff --git a/vendor/gopl.io/ch5/wait/wait.go b/vendor/gopl.io/ch5/wait/wait.go new file mode 100644 index 0000000..f5313e7 --- /dev/null +++ b/vendor/gopl.io/ch5/wait/wait.go @@ -0,0 +1,50 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 130. + +// The wait program waits for an HTTP server to start responding. +package main + +import ( + "fmt" + "log" + "net/http" + "os" + "time" +) + +//!+ +// WaitForServer attempts to contact the server of a URL. +// It tries for one minute using exponential back-off. +// It reports an error if all attempts fail. +func WaitForServer(url string) error { + const timeout = 1 * time.Minute + deadline := time.Now().Add(timeout) + for tries := 0; time.Now().Before(deadline); tries++ { + _, err := http.Head(url) + if err == nil { + return nil // success + } + log.Printf("server not responding (%s); retrying...", err) + time.Sleep(time.Second << uint(tries)) // exponential back-off + } + return fmt.Errorf("server %s failed to respond after %s", url, timeout) +} + +//!- + +func main() { + if len(os.Args) != 2 { + fmt.Fprintf(os.Stderr, "usage: wait url\n") + os.Exit(1) + } + url := os.Args[1] + //!+main + // (In function main.) + if err := WaitForServer(url); err != nil { + fmt.Fprintf(os.Stderr, "Site is down: %v\n", err) + os.Exit(1) + } + //!-main +} diff --git a/vendor/gopl.io/ch6/coloredpoint/main.go b/vendor/gopl.io/ch6/coloredpoint/main.go new file mode 100644 index 0000000..4b2335c --- /dev/null +++ b/vendor/gopl.io/ch6/coloredpoint/main.go @@ -0,0 +1,89 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 161. + +// Coloredpoint demonstrates struct embedding. +package main + +import ( + "fmt" + "math" +) + +//!+decl +import "image/color" + +type Point struct{ X, Y float64 } + +type ColoredPoint struct { + Point + Color color.RGBA +} + +//!-decl + +func (p Point) Distance(q Point) float64 { + dX := q.X - p.X + dY := q.Y - p.Y + return math.Sqrt(dX*dX + dY*dY) +} + +func (p *Point) ScaleBy(factor float64) { + p.X *= factor + p.Y *= factor +} + +func main() { + //!+main + red := color.RGBA{255, 0, 0, 255} + blue := color.RGBA{0, 0, 255, 255} + var p = ColoredPoint{Point{1, 1}, red} + var q = ColoredPoint{Point{5, 4}, blue} + fmt.Println(p.Distance(q.Point)) // "5" + p.ScaleBy(2) + q.ScaleBy(2) + fmt.Println(p.Distance(q.Point)) // "10" + //!-main +} + +/* +//!+error + p.Distance(q) // compile error: cannot use q (ColoredPoint) as Point +//!-error +*/ + +func init() { + //!+methodexpr + p := Point{1, 2} + q := Point{4, 6} + + distance := Point.Distance // method expression + fmt.Println(distance(p, q)) // "5" + fmt.Printf("%T\n", distance) // "func(Point, Point) float64" + + scale := (*Point).ScaleBy + scale(&p, 2) + fmt.Println(p) // "{2 4}" + fmt.Printf("%T\n", scale) // "func(*Point, float64)" + //!-methodexpr +} + +func init() { + red := color.RGBA{255, 0, 0, 255} + blue := color.RGBA{0, 0, 255, 255} + + //!+indirect + type ColoredPoint struct { + *Point + Color color.RGBA + } + + p := ColoredPoint{&Point{1, 1}, red} + q := ColoredPoint{&Point{5, 4}, blue} + fmt.Println(p.Distance(*q.Point)) // "5" + q.Point = p.Point // p and q now share the same Point + p.ScaleBy(2) + fmt.Println(*p.Point, *q.Point) // "{2 2} {2 2}" + //!-indirect +} diff --git a/vendor/gopl.io/ch6/geometry/geometry.go b/vendor/gopl.io/ch6/geometry/geometry.go new file mode 100644 index 0000000..2400e3e --- /dev/null +++ b/vendor/gopl.io/ch6/geometry/geometry.go @@ -0,0 +1,42 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 156. + +// Package geometry defines simple types for plane geometry. +//!+point +package geometry + +import "math" + +type Point struct{ X, Y float64 } + +// traditional function +func Distance(p, q Point) float64 { + return math.Hypot(q.X-p.X, q.Y-p.Y) +} + +// same thing, but as a method of the Point type +func (p Point) Distance(q Point) float64 { + return math.Hypot(q.X-p.X, q.Y-p.Y) +} + +//!-point + +//!+path + +// A Path is a journey connecting the points with straight lines. +type Path []Point + +// Distance returns the distance traveled along the path. +func (path Path) Distance() float64 { + sum := 0.0 + for i := range path { + if i > 0 { + sum += path[i-1].Distance(path[i]) + } + } + return sum +} + +//!-path diff --git a/vendor/gopl.io/ch6/intset/intset.go b/vendor/gopl.io/ch6/intset/intset.go new file mode 100644 index 0000000..78227e5 --- /dev/null +++ b/vendor/gopl.io/ch6/intset/intset.go @@ -0,0 +1,73 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 165. + +// Package intset provides a set of integers based on a bit vector. +package intset + +import ( + "bytes" + "fmt" +) + +//!+intset + +// An IntSet is a set of small non-negative integers. +// Its zero value represents the empty set. +type IntSet struct { + words []uint64 +} + +// Has reports whether the set contains the non-negative value x. +func (s *IntSet) Has(x int) bool { + word, bit := x/64, uint(x%64) + return word < len(s.words) && s.words[word]&(1<= len(s.words) { + s.words = append(s.words, 0) + } + s.words[word] |= 1 << bit +} + +// UnionWith sets s to the union of s and t. +func (s *IntSet) UnionWith(t *IntSet) { + for i, tword := range t.words { + if i < len(s.words) { + s.words[i] |= tword + } else { + s.words = append(s.words, tword) + } + } +} + +//!-intset + +//!+string + +// String returns the set as a string of the form "{1 2 3}". +func (s *IntSet) String() string { + var buf bytes.Buffer + buf.WriteByte('{') + for i, word := range s.words { + if word == 0 { + continue + } + for j := 0; j < 64; j++ { + if word&(1< len("{") { + buf.WriteByte(' ') + } + fmt.Fprintf(&buf, "%d", 64*i+j) + } + } + } + buf.WriteByte('}') + return buf.String() +} + +//!-string diff --git a/vendor/gopl.io/ch6/intset/intset_test.go b/vendor/gopl.io/ch6/intset/intset_test.go new file mode 100644 index 0000000..620a39e --- /dev/null +++ b/vendor/gopl.io/ch6/intset/intset_test.go @@ -0,0 +1,50 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package intset + +import "fmt" + +func Example_one() { + //!+main + var x, y IntSet + x.Add(1) + x.Add(144) + x.Add(9) + fmt.Println(x.String()) // "{1 9 144}" + + y.Add(9) + y.Add(42) + fmt.Println(y.String()) // "{9 42}" + + x.UnionWith(&y) + fmt.Println(x.String()) // "{1 9 42 144}" + + fmt.Println(x.Has(9), x.Has(123)) // "true false" + //!-main + + // Output: + // {1 9 144} + // {9 42} + // {1 9 42 144} + // true false +} + +func Example_two() { + var x IntSet + x.Add(1) + x.Add(144) + x.Add(9) + x.Add(42) + + //!+note + fmt.Println(&x) // "{1 9 42 144}" + fmt.Println(x.String()) // "{1 9 42 144}" + fmt.Println(x) // "{[4398046511618 0 65536]}" + //!-note + + // Output: + // {1 9 42 144} + // {1 9 42 144} + // {[4398046511618 0 65536]} +} diff --git a/vendor/gopl.io/ch6/urlvalues/main.go b/vendor/gopl.io/ch6/urlvalues/main.go new file mode 100644 index 0000000..7e226d5 --- /dev/null +++ b/vendor/gopl.io/ch6/urlvalues/main.go @@ -0,0 +1,53 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 160. + +// The urlvalues command demonstrates a map type with methods. +package main + +/* +//!+values +package url + +// Values maps a string key to a list of values. +type Values map[string][]string + +// Get returns the first value associated with the given key, +// or "" if there are none. +func (v Values) Get(key string) string { + if vs := v[key]; len(vs) > 0 { + return vs[0] + } + return "" +} + +// Add adds the value to key. +// It appends to any existing values associated with key. +func (v Values) Add(key, value string) { + v[key] = append(v[key], value) +} +//!-values +*/ + +import ( + "fmt" + "net/url" +) + +func main() { + //!+main + m := url.Values{"lang": {"en"}} // direct construction + m.Add("item", "1") + m.Add("item", "2") + + fmt.Println(m.Get("lang")) // "en" + fmt.Println(m.Get("q")) // "" + fmt.Println(m.Get("item")) // "1" (first value) + fmt.Println(m["item"]) // "[1 2]" (direct map access) + + m = nil + fmt.Println(m.Get("item")) // "" + m.Add("item", "3") // panic: assignment to entry in nil map + //!-main +} diff --git a/vendor/gopl.io/ch7/bytecounter/main.go b/vendor/gopl.io/ch7/bytecounter/main.go new file mode 100644 index 0000000..cb6e175 --- /dev/null +++ b/vendor/gopl.io/ch7/bytecounter/main.go @@ -0,0 +1,35 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 173. + +// Bytecounter demonstrates an implementation of io.Writer that counts bytes. +package main + +import ( + "fmt" +) + +//!+bytecounter + +type ByteCounter int + +func (c *ByteCounter) Write(p []byte) (int, error) { + *c += ByteCounter(len(p)) // convert int to ByteCounter + return len(p), nil +} + +//!-bytecounter + +func main() { + //!+main + var c ByteCounter + c.Write([]byte("hello")) + fmt.Println(c) // "5", = len("hello") + + c = 0 // reset the counter + var name = "Dolly" + fmt.Fprintf(&c, "hello, %s", name) + fmt.Println(c) // "12", = len("hello, Dolly") + //!-main +} diff --git a/vendor/gopl.io/ch7/eval/ast.go b/vendor/gopl.io/ch7/eval/ast.go new file mode 100644 index 0000000..4b6f381 --- /dev/null +++ b/vendor/gopl.io/ch7/eval/ast.go @@ -0,0 +1,40 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package eval + +// An Expr is an arithmetic expression. +type Expr interface { + // Eval returns the value of this Expr in the environment env. + Eval(env Env) float64 + // Check reports errors in this Expr and adds its Vars to the set. + Check(vars map[Var]bool) error +} + +//!+ast + +// A Var identifies a variable, e.g., x. +type Var string + +// A literal is a numeric constant, e.g., 3.141. +type literal float64 + +// A unary represents a unary operator expression, e.g., -x. +type unary struct { + op rune // one of '+', '-' + x Expr +} + +// A binary represents a binary operator expression, e.g., x+y. +type binary struct { + op rune // one of '+', '-', '*', '/' + x, y Expr +} + +// A call represents a function call expression, e.g., sin(x). +type call struct { + fn string // one of "pow", "sin", "sqrt" + args []Expr +} + +//!-ast diff --git a/vendor/gopl.io/ch7/eval/check.go b/vendor/gopl.io/ch7/eval/check.go new file mode 100644 index 0000000..7fddcbe --- /dev/null +++ b/vendor/gopl.io/ch7/eval/check.go @@ -0,0 +1,58 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package eval + +import ( + "fmt" + "strings" +) + +//!+Check + +func (v Var) Check(vars map[Var]bool) error { + vars[v] = true + return nil +} + +func (literal) Check(vars map[Var]bool) error { + return nil +} + +func (u unary) Check(vars map[Var]bool) error { + if !strings.ContainsRune("+-", u.op) { + return fmt.Errorf("unexpected unary op %q", u.op) + } + return u.x.Check(vars) +} + +func (b binary) Check(vars map[Var]bool) error { + if !strings.ContainsRune("+-*/", b.op) { + return fmt.Errorf("unexpected binary op %q", b.op) + } + if err := b.x.Check(vars); err != nil { + return err + } + return b.y.Check(vars) +} + +func (c call) Check(vars map[Var]bool) error { + arity, ok := numParams[c.fn] + if !ok { + return fmt.Errorf("unknown function %q", c.fn) + } + if len(c.args) != arity { + return fmt.Errorf("call to %s has %d args, want %d", + c.fn, len(c.args), arity) + } + for _, arg := range c.args { + if err := arg.Check(vars); err != nil { + return err + } + } + return nil +} + +var numParams = map[string]int{"pow": 2, "sin": 1, "sqrt": 1} + +//!-Check diff --git a/vendor/gopl.io/ch7/eval/coverage_test.go b/vendor/gopl.io/ch7/eval/coverage_test.go new file mode 100644 index 0000000..190dd37 --- /dev/null +++ b/vendor/gopl.io/ch7/eval/coverage_test.go @@ -0,0 +1,48 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package eval + +import ( + "fmt" + "math" + "testing" +) + +//!+TestCoverage +func TestCoverage(t *testing.T) { + var tests = []struct { + input string + env Env + want string // expected error from Parse/Check or result from Eval + }{ + {"x % 2", nil, "unexpected '%'"}, + {"!true", nil, "unexpected '!'"}, + {"log(10)", nil, `unknown function "log"`}, + {"sqrt(1, 2)", nil, "call to sqrt has 2 args, want 1"}, + {"sqrt(A / pi)", Env{"A": 87616, "pi": math.Pi}, "167"}, + {"pow(x, 3) + pow(y, 3)", Env{"x": 9, "y": 10}, "1729"}, + {"5 / 9 * (F - 32)", Env{"F": -40}, "-40"}, + } + + for _, test := range tests { + expr, err := Parse(test.input) + if err == nil { + err = expr.Check(map[Var]bool{}) + } + if err != nil { + if err.Error() != test.want { + t.Errorf("%s: got %q, want %q", test.input, err, test.want) + } + continue + } + + got := fmt.Sprintf("%.6g", expr.Eval(test.env)) + if got != test.want { + t.Errorf("%s: %v => %s, want %s", + test.input, test.env, got, test.want) + } + } +} + +//!-TestCoverage diff --git a/vendor/gopl.io/ch7/eval/eval.go b/vendor/gopl.io/ch7/eval/eval.go new file mode 100644 index 0000000..4ab1dd7 --- /dev/null +++ b/vendor/gopl.io/ch7/eval/eval.go @@ -0,0 +1,70 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 198. + +// Package eval provides an expression evaluator. +package eval + +import ( + "fmt" + "math" +) + +//!+env + +type Env map[Var]float64 + +//!-env + +//!+Eval1 + +func (v Var) Eval(env Env) float64 { + return env[v] +} + +func (l literal) Eval(_ Env) float64 { + return float64(l) +} + +//!-Eval1 + +//!+Eval2 + +func (u unary) Eval(env Env) float64 { + switch u.op { + case '+': + return +u.x.Eval(env) + case '-': + return -u.x.Eval(env) + } + panic(fmt.Sprintf("unsupported unary operator: %q", u.op)) +} + +func (b binary) Eval(env Env) float64 { + switch b.op { + case '+': + return b.x.Eval(env) + b.y.Eval(env) + case '-': + return b.x.Eval(env) - b.y.Eval(env) + case '*': + return b.x.Eval(env) * b.y.Eval(env) + case '/': + return b.x.Eval(env) / b.y.Eval(env) + } + panic(fmt.Sprintf("unsupported binary operator: %q", b.op)) +} + +func (c call) Eval(env Env) float64 { + switch c.fn { + case "pow": + return math.Pow(c.args[0].Eval(env), c.args[1].Eval(env)) + case "sin": + return math.Sin(c.args[0].Eval(env)) + case "sqrt": + return math.Sqrt(c.args[0].Eval(env)) + } + panic(fmt.Sprintf("unsupported function call: %s", c.fn)) +} + +//!-Eval2 diff --git a/vendor/gopl.io/ch7/eval/eval_test.go b/vendor/gopl.io/ch7/eval/eval_test.go new file mode 100644 index 0000000..88905cd --- /dev/null +++ b/vendor/gopl.io/ch7/eval/eval_test.go @@ -0,0 +1,113 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package eval + +import ( + "fmt" + "math" + "testing" +) + +//!+Eval +func TestEval(t *testing.T) { + tests := []struct { + expr string + env Env + want string + }{ + {"sqrt(A / pi)", Env{"A": 87616, "pi": math.Pi}, "167"}, + {"pow(x, 3) + pow(y, 3)", Env{"x": 12, "y": 1}, "1729"}, + {"pow(x, 3) + pow(y, 3)", Env{"x": 9, "y": 10}, "1729"}, + {"5 / 9 * (F - 32)", Env{"F": -40}, "-40"}, + {"5 / 9 * (F - 32)", Env{"F": 32}, "0"}, + {"5 / 9 * (F - 32)", Env{"F": 212}, "100"}, + //!-Eval + // additional tests that don't appear in the book + {"-1 + -x", Env{"x": 1}, "-2"}, + {"-1 - x", Env{"x": 1}, "-2"}, + //!+Eval + } + var prevExpr string + for _, test := range tests { + // Print expr only when it changes. + if test.expr != prevExpr { + fmt.Printf("\n%s\n", test.expr) + prevExpr = test.expr + } + expr, err := Parse(test.expr) + if err != nil { + t.Error(err) // parse error + continue + } + got := fmt.Sprintf("%.6g", expr.Eval(test.env)) + fmt.Printf("\t%v => %s\n", test.env, got) + if got != test.want { + t.Errorf("%s.Eval() in %v = %q, want %q\n", + test.expr, test.env, got, test.want) + } + } +} + +//!-Eval + +/* +//!+output +sqrt(A / pi) + map[A:87616 pi:3.141592653589793] => 167 + +pow(x, 3) + pow(y, 3) + map[x:12 y:1] => 1729 + map[x:9 y:10] => 1729 + +5 / 9 * (F - 32) + map[F:-40] => -40 + map[F:32] => 0 + map[F:212] => 100 +//!-output + +// Additional outputs that don't appear in the book. + +-1 - x + map[x:1] => -2 + +-1 + -x + map[x:1] => -2 +*/ + +func TestErrors(t *testing.T) { + for _, test := range []struct{ expr, wantErr string }{ + {"x % 2", "unexpected '%'"}, + {"math.Pi", "unexpected '.'"}, + {"!true", "unexpected '!'"}, + {`"hello"`, "unexpected '\"'"}, + {"log(10)", `unknown function "log"`}, + {"sqrt(1, 2)", "call to sqrt has 2 args, want 1"}, + } { + expr, err := Parse(test.expr) + if err == nil { + vars := make(map[Var]bool) + err = expr.Check(vars) + if err == nil { + t.Errorf("unexpected success: %s", test.expr) + continue + } + } + fmt.Printf("%-20s%v\n", test.expr, err) // (for book) + if err.Error() != test.wantErr { + t.Errorf("got error %s, want %s", err, test.wantErr) + } + } +} + +/* +//!+errors +x % 2 unexpected '%' +math.Pi unexpected '.' +!true unexpected '!' +"hello" unexpected '"' + +log(10) unknown function "log" +sqrt(1, 2) call to sqrt has 2 args, want 1 +//!-errors +*/ diff --git a/vendor/gopl.io/ch7/eval/parse.go b/vendor/gopl.io/ch7/eval/parse.go new file mode 100644 index 0000000..677e9a0 --- /dev/null +++ b/vendor/gopl.io/ch7/eval/parse.go @@ -0,0 +1,160 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package eval + +import ( + "fmt" + "strconv" + "strings" + "text/scanner" +) + +// ---- lexer ---- + +// This lexer is similar to the one described in Chapter 13. +type lexer struct { + scan scanner.Scanner + token rune // current lookahead token +} + +func (lex *lexer) next() { lex.token = lex.scan.Scan() } +func (lex *lexer) text() string { return lex.scan.TokenText() } + +type lexPanic string + +// describe returns a string describing the current token, for use in errors. +func (lex *lexer) describe() string { + switch lex.token { + case scanner.EOF: + return "end of file" + case scanner.Ident: + return fmt.Sprintf("identifier %s", lex.text()) + case scanner.Int, scanner.Float: + return fmt.Sprintf("number %s", lex.text()) + } + return fmt.Sprintf("%q", rune(lex.token)) // any other rune +} + +func precedence(op rune) int { + switch op { + case '*', '/': + return 2 + case '+', '-': + return 1 + } + return 0 +} + +// ---- parser ---- + +// Parse parses the input string as an arithmetic expression. +// +// expr = num a literal number, e.g., 3.14159 +// | id a variable name, e.g., x +// | id '(' expr ',' ... ')' a function call +// | '-' expr a unary operator (+-) +// | expr '+' expr a binary operator (+-*/) +// +func Parse(input string) (_ Expr, err error) { + defer func() { + switch x := recover().(type) { + case nil: + // no panic + case lexPanic: + err = fmt.Errorf("%s", x) + default: + // unexpected panic: resume state of panic. + panic(x) + } + }() + lex := new(lexer) + lex.scan.Init(strings.NewReader(input)) + lex.scan.Mode = scanner.ScanIdents | scanner.ScanInts | scanner.ScanFloats + lex.next() // initial lookahead + e := parseExpr(lex) + if lex.token != scanner.EOF { + return nil, fmt.Errorf("unexpected %s", lex.describe()) + } + return e, nil +} + +func parseExpr(lex *lexer) Expr { return parseBinary(lex, 1) } + +// binary = unary ('+' binary)* +// parseBinary stops when it encounters an +// operator of lower precedence than prec1. +func parseBinary(lex *lexer, prec1 int) Expr { + lhs := parseUnary(lex) + for prec := precedence(lex.token); prec >= prec1; prec-- { + for precedence(lex.token) == prec { + op := lex.token + lex.next() // consume operator + rhs := parseBinary(lex, prec+1) + lhs = binary{op, lhs, rhs} + } + } + return lhs +} + +// unary = '+' expr | primary +func parseUnary(lex *lexer) Expr { + if lex.token == '+' || lex.token == '-' { + op := lex.token + lex.next() // consume '+' or '-' + return unary{op, parseUnary(lex)} + } + return parsePrimary(lex) +} + +// primary = id +// | id '(' expr ',' ... ',' expr ')' +// | num +// | '(' expr ')' +func parsePrimary(lex *lexer) Expr { + switch lex.token { + case scanner.Ident: + id := lex.text() + lex.next() // consume Ident + if lex.token != '(' { + return Var(id) + } + lex.next() // consume '(' + var args []Expr + if lex.token != ')' { + for { + args = append(args, parseExpr(lex)) + if lex.token != ',' { + break + } + lex.next() // consume ',' + } + if lex.token != ')' { + msg := fmt.Sprintf("got %q, want ')'", lex.token) + panic(lexPanic(msg)) + } + } + lex.next() // consume ')' + return call{id, args} + + case scanner.Int, scanner.Float: + f, err := strconv.ParseFloat(lex.text(), 64) + if err != nil { + panic(lexPanic(err.Error())) + } + lex.next() // consume number + return literal(f) + + case '(': + lex.next() // consume ')' + e := parseExpr(lex) + if lex.token != ')' { + msg := fmt.Sprintf("got %s, want ')'", lex.describe()) + panic(lexPanic(msg)) + } + lex.next() // consume ')' + return e + } + msg := fmt.Sprintf("unexpected %s", lex.describe()) + panic(lexPanic(msg)) +} diff --git a/vendor/gopl.io/ch7/eval/print.go b/vendor/gopl.io/ch7/eval/print.go new file mode 100644 index 0000000..69bf2db --- /dev/null +++ b/vendor/gopl.io/ch7/eval/print.go @@ -0,0 +1,52 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package eval + +import ( + "bytes" + "fmt" +) + +// Format formats an expression as a string. +// It does not attempt to remove unnecessary parens. +func Format(e Expr) string { + var buf bytes.Buffer + write(&buf, e) + return buf.String() +} + +func write(buf *bytes.Buffer, e Expr) { + switch e := e.(type) { + case literal: + fmt.Fprintf(buf, "%g", e) + + case Var: + fmt.Fprintf(buf, "%s", e) + + case unary: + fmt.Fprintf(buf, "(%c", e.op) + write(buf, e.x) + buf.WriteByte(')') + + case binary: + buf.WriteByte('(') + write(buf, e.x) + fmt.Fprintf(buf, " %c ", e.op) + write(buf, e.y) + buf.WriteByte(')') + + case call: + fmt.Fprintf(buf, "%s(", e.fn) + for i, arg := range e.args { + if i > 0 { + buf.WriteString(", ") + } + write(buf, arg) + } + buf.WriteByte(')') + + default: + panic(fmt.Sprintf("unknown Expr: %T", e)) + } +} diff --git a/vendor/gopl.io/ch7/http1/main.go b/vendor/gopl.io/ch7/http1/main.go new file mode 100644 index 0000000..9e7b664 --- /dev/null +++ b/vendor/gopl.io/ch7/http1/main.go @@ -0,0 +1,46 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 191. + +// Http1 is a rudimentary e-commerce server. +package main + +import ( + "fmt" + "log" + "net/http" +) + +//!+main + +func main() { + db := database{"shoes": 50, "socks": 5} + log.Fatal(http.ListenAndServe("localhost:8000", db)) +} + +type dollars float32 + +func (d dollars) String() string { return fmt.Sprintf("$%.2f", d) } + +type database map[string]dollars + +func (db database) ServeHTTP(w http.ResponseWriter, req *http.Request) { + for item, price := range db { + fmt.Fprintf(w, "%s: %s\n", item, price) + } +} + +//!-main + +/* +//!+handler +package http + +type Handler interface { + ServeHTTP(w ResponseWriter, r *Request) +} + +func ListenAndServe(address string, h Handler) error +//!-handler +*/ diff --git a/vendor/gopl.io/ch7/http2/main.go b/vendor/gopl.io/ch7/http2/main.go new file mode 100644 index 0000000..78ba8bc --- /dev/null +++ b/vendor/gopl.io/ch7/http2/main.go @@ -0,0 +1,48 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 192. + +// Http2 is an e-commerce server with /list and /price endpoints. +package main + +import ( + "fmt" + "log" + "net/http" +) + +func main() { + db := database{"shoes": 50, "socks": 5} + log.Fatal(http.ListenAndServe("localhost:8000", db)) +} + +type dollars float32 + +func (d dollars) String() string { return fmt.Sprintf("$%.2f", d) } + +type database map[string]dollars + +//!+handler +func (db database) ServeHTTP(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/list": + for item, price := range db { + fmt.Fprintf(w, "%s: %s\n", item, price) + } + case "/price": + item := req.URL.Query().Get("item") + price, ok := db[item] + if !ok { + w.WriteHeader(http.StatusNotFound) // 404 + fmt.Fprintf(w, "no such item: %q\n", item) + return + } + fmt.Fprintf(w, "%s\n", price) + default: + w.WriteHeader(http.StatusNotFound) // 404 + fmt.Fprintf(w, "no such page: %s\n", req.URL) + } +} + +//!-handler diff --git a/vendor/gopl.io/ch7/http3/main.go b/vendor/gopl.io/ch7/http3/main.go new file mode 100644 index 0000000..816e2a2 --- /dev/null +++ b/vendor/gopl.io/ch7/http3/main.go @@ -0,0 +1,61 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 194. + +// Http3 is an e-commerce server that registers the /list and /price +// endpoints by calling (*http.ServeMux).Handle. +package main + +import ( + "fmt" + "log" + "net/http" +) + +type dollars float32 + +func (d dollars) String() string { return fmt.Sprintf("$%.2f", d) } + +//!+main + +func main() { + db := database{"shoes": 50, "socks": 5} + mux := http.NewServeMux() + mux.Handle("/list", http.HandlerFunc(db.list)) + mux.Handle("/price", http.HandlerFunc(db.price)) + log.Fatal(http.ListenAndServe("localhost:8000", mux)) +} + +type database map[string]dollars + +func (db database) list(w http.ResponseWriter, req *http.Request) { + for item, price := range db { + fmt.Fprintf(w, "%s: %s\n", item, price) + } +} + +func (db database) price(w http.ResponseWriter, req *http.Request) { + item := req.URL.Query().Get("item") + price, ok := db[item] + if !ok { + w.WriteHeader(http.StatusNotFound) // 404 + fmt.Fprintf(w, "no such item: %q\n", item) + return + } + fmt.Fprintf(w, "%s\n", price) +} + +//!-main + +/* +//!+handlerfunc +package http + +type HandlerFunc func(w ResponseWriter, r *Request) + +func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { + f(w, r) +} +//!-handlerfunc +*/ diff --git a/vendor/gopl.io/ch7/http3a/main.go b/vendor/gopl.io/ch7/http3a/main.go new file mode 100644 index 0000000..b682466 --- /dev/null +++ b/vendor/gopl.io/ch7/http3a/main.go @@ -0,0 +1,54 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 195. + +// Http3a is an e-commerce server that registers the /list and /price +// endpoints by calling (*http.ServeMux).HandleFunc. +package main + +import ( + "fmt" + "log" + "net/http" +) + +func main() { + db := database{"shoes": 50, "socks": 5} + mux := http.NewServeMux() + //!+main + mux.HandleFunc("/list", db.list) + mux.HandleFunc("/price", db.price) + //!-main + log.Fatal(http.ListenAndServe("localhost:8000", mux)) +} + +type database map[string]int + +func (db database) list(w http.ResponseWriter, req *http.Request) { + for item, price := range db { + fmt.Fprintf(w, "%s: $%d\n", item, price) + } +} + +func (db database) price(w http.ResponseWriter, req *http.Request) { + item := req.URL.Query().Get("item") + if price, ok := db[item]; ok { + fmt.Fprintf(w, "$%d\n", price) + } else { + w.WriteHeader(http.StatusNotFound) // 404 + fmt.Fprintf(w, "no such item: %q\n", item) + } +} + +/* +//!+handlerfunc +package http + +type HandlerFunc func(w ResponseWriter, r *Request) + +func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { + f(w, r) +} +//!-handlerfunc +*/ diff --git a/vendor/gopl.io/ch7/http4/main.go b/vendor/gopl.io/ch7/http4/main.go new file mode 100644 index 0000000..b207d7a --- /dev/null +++ b/vendor/gopl.io/ch7/http4/main.go @@ -0,0 +1,47 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 195. + +// Http4 is an e-commerce server that registers the /list and /price +// endpoint by calling http.HandleFunc. +package main + +import ( + "fmt" + "log" + "net/http" +) + +//!+main + +func main() { + db := database{"shoes": 50, "socks": 5} + http.HandleFunc("/list", db.list) + http.HandleFunc("/price", db.price) + log.Fatal(http.ListenAndServe("localhost:8000", nil)) +} + +//!-main + +type dollars float32 + +func (d dollars) String() string { return fmt.Sprintf("$%.2f", d) } + +type database map[string]dollars + +func (db database) list(w http.ResponseWriter, req *http.Request) { + for item, price := range db { + fmt.Fprintf(w, "%s: %s\n", item, price) + } +} + +func (db database) price(w http.ResponseWriter, req *http.Request) { + item := req.URL.Query().Get("item") + if price, ok := db[item]; ok { + fmt.Fprintf(w, "%s\n", price) + } else { + w.WriteHeader(http.StatusNotFound) // 404 + fmt.Fprintf(w, "no such item: %q\n", item) + } +} diff --git a/vendor/gopl.io/ch7/sleep/sleep.go b/vendor/gopl.io/ch7/sleep/sleep.go new file mode 100644 index 0000000..04f247e --- /dev/null +++ b/vendor/gopl.io/ch7/sleep/sleep.go @@ -0,0 +1,25 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 179. + +// The sleep program sleeps for a specified period of time. +package main + +import ( + "flag" + "fmt" + "time" +) + +//!+sleep +var period = flag.Duration("period", 1*time.Second, "sleep period") + +func main() { + flag.Parse() + fmt.Printf("Sleeping for %v...", *period) + time.Sleep(*period) + fmt.Println() +} + +//!-sleep diff --git a/vendor/gopl.io/ch7/sorting/main.go b/vendor/gopl.io/ch7/sorting/main.go new file mode 100644 index 0000000..be598d9 --- /dev/null +++ b/vendor/gopl.io/ch7/sorting/main.go @@ -0,0 +1,167 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 187. + +// Sorting sorts a music playlist into a variety of orders. +package main + +import ( + "fmt" + "os" + "sort" + "text/tabwriter" + "time" +) + +//!+main +type Track struct { + Title string + Artist string + Album string + Year int + Length time.Duration +} + +var tracks = []*Track{ + {"Go", "Delilah", "From the Roots Up", 2012, length("3m38s")}, + {"Go", "Moby", "Moby", 1992, length("3m37s")}, + {"Go Ahead", "Alicia Keys", "As I Am", 2007, length("4m36s")}, + {"Ready 2 Go", "Martin Solveig", "Smash", 2011, length("4m24s")}, +} + +func length(s string) time.Duration { + d, err := time.ParseDuration(s) + if err != nil { + panic(s) + } + return d +} + +//!-main + +//!+printTracks +func printTracks(tracks []*Track) { + const format = "%v\t%v\t%v\t%v\t%v\t\n" + tw := new(tabwriter.Writer).Init(os.Stdout, 0, 8, 2, ' ', 0) + fmt.Fprintf(tw, format, "Title", "Artist", "Album", "Year", "Length") + fmt.Fprintf(tw, format, "-----", "------", "-----", "----", "------") + for _, t := range tracks { + fmt.Fprintf(tw, format, t.Title, t.Artist, t.Album, t.Year, t.Length) + } + tw.Flush() // calculate column widths and print table +} + +//!-printTracks + +//!+artistcode +type byArtist []*Track + +func (x byArtist) Len() int { return len(x) } +func (x byArtist) Less(i, j int) bool { return x[i].Artist < x[j].Artist } +func (x byArtist) Swap(i, j int) { x[i], x[j] = x[j], x[i] } + +//!-artistcode + +//!+yearcode +type byYear []*Track + +func (x byYear) Len() int { return len(x) } +func (x byYear) Less(i, j int) bool { return x[i].Year < x[j].Year } +func (x byYear) Swap(i, j int) { x[i], x[j] = x[j], x[i] } + +//!-yearcode + +func main() { + fmt.Println("byArtist:") + sort.Sort(byArtist(tracks)) + printTracks(tracks) + + fmt.Println("\nReverse(byArtist):") + sort.Sort(sort.Reverse(byArtist(tracks))) + printTracks(tracks) + + fmt.Println("\nbyYear:") + sort.Sort(byYear(tracks)) + printTracks(tracks) + + fmt.Println("\nCustom:") + //!+customcall + sort.Sort(customSort{tracks, func(x, y *Track) bool { + if x.Title != y.Title { + return x.Title < y.Title + } + if x.Year != y.Year { + return x.Year < y.Year + } + if x.Length != y.Length { + return x.Length < y.Length + } + return false + }}) + //!-customcall + printTracks(tracks) +} + +/* +//!+artistoutput +Title Artist Album Year Length +----- ------ ----- ---- ------ +Go Ahead Alicia Keys As I Am 2007 4m36s +Go Delilah From the Roots Up 2012 3m38s +Ready 2 Go Martin Solveig Smash 2011 4m24s +Go Moby Moby 1992 3m37s +//!-artistoutput + +//!+artistrevoutput +Title Artist Album Year Length +----- ------ ----- ---- ------ +Go Moby Moby 1992 3m37s +Ready 2 Go Martin Solveig Smash 2011 4m24s +Go Delilah From the Roots Up 2012 3m38s +Go Ahead Alicia Keys As I Am 2007 4m36s +//!-artistrevoutput + +//!+yearoutput +Title Artist Album Year Length +----- ------ ----- ---- ------ +Go Moby Moby 1992 3m37s +Go Ahead Alicia Keys As I Am 2007 4m36s +Ready 2 Go Martin Solveig Smash 2011 4m24s +Go Delilah From the Roots Up 2012 3m38s +//!-yearoutput + +//!+customout +Title Artist Album Year Length +----- ------ ----- ---- ------ +Go Moby Moby 1992 3m37s +Go Delilah From the Roots Up 2012 3m38s +Go Ahead Alicia Keys As I Am 2007 4m36s +Ready 2 Go Martin Solveig Smash 2011 4m24s +//!-customout +*/ + +//!+customcode +type customSort struct { + t []*Track + less func(x, y *Track) bool +} + +func (x customSort) Len() int { return len(x.t) } +func (x customSort) Less(i, j int) bool { return x.less(x.t[i], x.t[j]) } +func (x customSort) Swap(i, j int) { x.t[i], x.t[j] = x.t[j], x.t[i] } + +//!-customcode + +func init() { + //!+ints + values := []int{3, 1, 4, 1} + fmt.Println(sort.IntsAreSorted(values)) // "false" + sort.Ints(values) + fmt.Println(values) // "[1 1 3 4]" + fmt.Println(sort.IntsAreSorted(values)) // "true" + sort.Sort(sort.Reverse(sort.IntSlice(values))) + fmt.Println(values) // "[4 3 1 1]" + fmt.Println(sort.IntsAreSorted(values)) // "false" + //!-ints +} diff --git a/vendor/gopl.io/ch7/surface/surface.go b/vendor/gopl.io/ch7/surface/surface.go new file mode 100644 index 0000000..ed768ba --- /dev/null +++ b/vendor/gopl.io/ch7/surface/surface.go @@ -0,0 +1,112 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 203. + +// The surface program plots the 3-D surface of a user-provided function. +package main + +import ( + "fmt" + "io" + "log" + "math" + "net/http" +) + +//!+parseAndCheck +import "gopl.io/ch7/eval" + +//!-parseAndCheck + +// -- copied from gopl.io/ch3/surface -- + +const ( + width, height = 600, 320 // canvas size in pixels + cells = 100 // number of grid cells + xyrange = 30.0 // x, y axis range (-xyrange..+xyrange) + xyscale = width / 2 / xyrange // pixels per x or y unit + zscale = height * 0.4 // pixels per z unit +) + +var sin30, cos30 = 0.5, math.Sqrt(3.0 / 4.0) // sin(30°), cos(30°) + +func corner(f func(x, y float64) float64, i, j int) (float64, float64) { + // find point (x,y) at corner of cell (i,j) + x := xyrange * (float64(i)/cells - 0.5) + y := xyrange * (float64(j)/cells - 0.5) + + z := f(x, y) // compute surface height z + + // project (x,y,z) isometrically onto 2-D SVG canvas (sx,sy) + sx := width/2 + (x-y)*cos30*xyscale + sy := height/2 + (x+y)*sin30*xyscale - z*zscale + return sx, sy +} + +func surface(w io.Writer, f func(x, y float64) float64) { + fmt.Fprintf(w, "", width, height) + for i := 0; i < cells; i++ { + for j := 0; j < cells; j++ { + ax, ay := corner(f, i+1, j) + bx, by := corner(f, i, j) + cx, cy := corner(f, i, j+1) + dx, dy := corner(f, i+1, j+1) + fmt.Fprintf(w, "\n", + ax, ay, bx, by, cx, cy, dx, dy) + } + } + fmt.Fprintln(w, "") +} + +// -- main code for gopl.io/ch7/surface -- + +//!+parseAndCheck +func parseAndCheck(s string) (eval.Expr, error) { + if s == "" { + return nil, fmt.Errorf("empty expression") + } + expr, err := eval.Parse(s) + if err != nil { + return nil, err + } + vars := make(map[eval.Var]bool) + if err := expr.Check(vars); err != nil { + return nil, err + } + for v := range vars { + if v != "x" && v != "y" && v != "r" { + return nil, fmt.Errorf("undefined variable: %s", v) + } + } + return expr, nil +} + +//!-parseAndCheck + +//!+plot +func plot(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + expr, err := parseAndCheck(r.Form.Get("expr")) + if err != nil { + http.Error(w, "bad expr: "+err.Error(), http.StatusBadRequest) + return + } + w.Header().Set("Content-Type", "image/svg+xml") + surface(w, func(x, y float64) float64 { + r := math.Hypot(x, y) // distance from (0,0) + return expr.Eval(eval.Env{"x": x, "y": y, "r": r}) + }) +} + +//!-plot + +//!+main +func main() { + http.HandleFunc("/plot", plot) + log.Fatal(http.ListenAndServe("localhost:8000", nil)) +} + +//!-main diff --git a/vendor/gopl.io/ch7/tempconv/tempconv.go b/vendor/gopl.io/ch7/tempconv/tempconv.go new file mode 100644 index 0000000..6c3ef41 --- /dev/null +++ b/vendor/gopl.io/ch7/tempconv/tempconv.go @@ -0,0 +1,66 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 180. + +// Package tempconv performs Celsius and Fahrenheit temperature computations. +package tempconv + +import ( + "flag" + "fmt" +) + +type Celsius float64 +type Fahrenheit float64 + +func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9.0/5.0 + 32.0) } +func FToC(f Fahrenheit) Celsius { return Celsius((f - 32.0) * 5.0 / 9.0) } + +func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) } + +/* +//!+flagvalue +package flag + +// Value is the interface to the value stored in a flag. +type Value interface { + String() string + Set(string) error +} +//!-flagvalue +*/ + +//!+celsiusFlag +// *celsiusFlag satisfies the flag.Value interface. +type celsiusFlag struct{ Celsius } + +func (f *celsiusFlag) Set(s string) error { + var unit string + var value float64 + fmt.Sscanf(s, "%f%s", &value, &unit) // no error check needed + switch unit { + case "C", "°C": + f.Celsius = Celsius(value) + return nil + case "F", "°F": + f.Celsius = FToC(Fahrenheit(value)) + return nil + } + return fmt.Errorf("invalid temperature %q", s) +} + +//!-celsiusFlag + +//!+CelsiusFlag + +// CelsiusFlag defines a Celsius flag with the specified name, +// default value, and usage, and returns the address of the flag variable. +// The flag argument must have a quantity and a unit, e.g., "100C". +func CelsiusFlag(name string, value Celsius, usage string) *Celsius { + f := celsiusFlag{value} + flag.CommandLine.Var(&f, name, usage) + return &f.Celsius +} + +//!-CelsiusFlag diff --git a/vendor/gopl.io/ch7/tempconv/tempconv.go.~master~ b/vendor/gopl.io/ch7/tempconv/tempconv.go.~master~ new file mode 100644 index 0000000..5ee2de8 --- /dev/null +++ b/vendor/gopl.io/ch7/tempconv/tempconv.go.~master~ @@ -0,0 +1,64 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + + +// Package tempconv performs Celsius and Fahrenheit temperature computations. +package tempconv + +import ( + "flag" + "fmt" +) + +type Celsius float64 +type Fahrenheit float64 + +func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9.0/5.0 + 32.0) } +func FToC(f Fahrenheit) Celsius { return Celsius((f - 32.0) * 5.0 / 9.0) } + +func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) } + +/* +//!+flagvalue +package flag + +// Value is the interface to the value stored in a flag. +type Value interface { + String() string + Set(string) error +} +//!-flagvalue +*/ + +//!+celsiusflag +// *celsiusFlag satisfies the flag.Value interface. +type celsiusFlag struct{ Celsius } + +func (f *celsiusFlag) Set(s string) error { + var unit string + var value float64 + fmt.Sscanf(s, "%f%s", &value, &unit) // no error check needed + switch unit { + case "C", "°C": + f.Celsius = Celsius(value) + return nil + case "F", "°F": + f.Celsius = FToC(Fahrenheit(value)) + return nil + } + return fmt.Errorf("invalid temperature %q", s) +} + +//!-celsiusflag + +//!+Celsiusflag +// CelsiusFlag defines a Celsius flag with the specified name, +// default value, and usage, and returns the address of the flag variable. +// The flag argument must have a quantity and a unit, e.g., "100C". +func CelsiusFlag(name string, value Celsius, usage string) *Celsius { + f := celsiusFlag{value} + flag.CommandLine.Var(&f, name, usage) + return &f.Celsius +} + +//!-Celsiusflag diff --git a/vendor/gopl.io/ch7/tempflag/tempflag.go b/vendor/gopl.io/ch7/tempflag/tempflag.go new file mode 100644 index 0000000..6f6a4e7 --- /dev/null +++ b/vendor/gopl.io/ch7/tempflag/tempflag.go @@ -0,0 +1,24 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 181. + +// Tempflag prints the value of its -temp (temperature) flag. +package main + +import ( + "flag" + "fmt" + + "gopl.io/ch7/tempconv" +) + +//!+ +var temp = tempconv.CelsiusFlag("temp", 20.0, "the temperature") + +func main() { + flag.Parse() + fmt.Println(*temp) +} + +//!- diff --git a/vendor/gopl.io/ch7/xmlselect/main.go b/vendor/gopl.io/ch7/xmlselect/main.go new file mode 100644 index 0000000..66cea65 --- /dev/null +++ b/vendor/gopl.io/ch7/xmlselect/main.go @@ -0,0 +1,56 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 214. +//!+ + +// Xmlselect prints the text of selected elements of an XML document. +package main + +import ( + "encoding/xml" + "fmt" + "io" + "os" + "strings" +) + +func main() { + dec := xml.NewDecoder(os.Stdin) + var stack []string // stack of element names + for { + tok, err := dec.Token() + if err == io.EOF { + break + } else if err != nil { + fmt.Fprintf(os.Stderr, "xmlselect: %v\n", err) + os.Exit(1) + } + switch tok := tok.(type) { + case xml.StartElement: + stack = append(stack, tok.Name.Local) // push + case xml.EndElement: + stack = stack[:len(stack)-1] // pop + case xml.CharData: + if containsAll(stack, os.Args[1:]) { + fmt.Printf("%s: %s\n", strings.Join(stack, " "), tok) + } + } + } +} + +// containsAll reports whether x contains the elements of y, in order. +func containsAll(x, y []string) bool { + for len(y) <= len(x) { + if len(y) == 0 { + return true + } + if x[0] == y[0] { + y = y[1:] + } + x = x[1:] + } + return false +} + +//!- diff --git a/vendor/gopl.io/ch8/cake/cake.go b/vendor/gopl.io/ch8/cake/cake.go new file mode 100644 index 0000000..8de0c3d --- /dev/null +++ b/vendor/gopl.io/ch8/cake/cake.go @@ -0,0 +1,89 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 234. + +// Package cake provides a simulation of +// a concurrent cake shop with numerous parameters. +// +// Use this command to run the benchmarks: +// $ go test -bench=. gopl.io/ch8/cake +package cake + +import ( + "fmt" + "math/rand" + "time" +) + +type Shop struct { + Verbose bool + Cakes int // number of cakes to bake + BakeTime time.Duration // time to bake one cake + BakeStdDev time.Duration // standard deviation of baking time + BakeBuf int // buffer slots between baking and icing + NumIcers int // number of cooks doing icing + IceTime time.Duration // time to ice one cake + IceStdDev time.Duration // standard deviation of icing time + IceBuf int // buffer slots between icing and inscribing + InscribeTime time.Duration // time to inscribe one cake + InscribeStdDev time.Duration // standard deviation of inscribing time +} + +type cake int + +func (s *Shop) baker(baked chan<- cake) { + for i := 0; i < s.Cakes; i++ { + c := cake(i) + if s.Verbose { + fmt.Println("baking", c) + } + work(s.BakeTime, s.BakeStdDev) + baked <- c + } + close(baked) +} + +func (s *Shop) icer(iced chan<- cake, baked <-chan cake) { + for c := range baked { + if s.Verbose { + fmt.Println("icing", c) + } + work(s.IceTime, s.IceStdDev) + iced <- c + } +} + +func (s *Shop) inscriber(iced <-chan cake) { + for i := 0; i < s.Cakes; i++ { + c := <-iced + if s.Verbose { + fmt.Println("inscribing", c) + } + work(s.InscribeTime, s.InscribeStdDev) + if s.Verbose { + fmt.Println("finished", c) + } + } +} + +// Work runs the simulation 'runs' times. +func (s *Shop) Work(runs int) { + for run := 0; run < runs; run++ { + baked := make(chan cake, s.BakeBuf) + iced := make(chan cake, s.IceBuf) + go s.baker(baked) + for i := 0; i < s.NumIcers; i++ { + go s.icer(iced, baked) + } + s.inscriber(iced) + } +} + +// work blocks the calling goroutine for a period of time +// that is normally distributed around d +// with a standard deviation of stddev. +func work(d, stddev time.Duration) { + delay := d + time.Duration(rand.NormFloat64()*float64(stddev)) + time.Sleep(delay) +} diff --git a/vendor/gopl.io/ch8/cake/cake_test.go b/vendor/gopl.io/ch8/cake/cake_test.go new file mode 100644 index 0000000..f8fea0e --- /dev/null +++ b/vendor/gopl.io/ch8/cake/cake_test.go @@ -0,0 +1,74 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package cake_test + +import ( + "testing" + "time" + + "gopl.io/ch8/cake" +) + +var defaults = cake.Shop{ + Verbose: testing.Verbose(), + Cakes: 20, + BakeTime: 10 * time.Millisecond, + NumIcers: 1, + IceTime: 10 * time.Millisecond, + InscribeTime: 10 * time.Millisecond, +} + +func Benchmark(b *testing.B) { + // Baseline: one baker, one icer, one inscriber. + // Each step takes exactly 10ms. No buffers. + cakeshop := defaults + cakeshop.Work(b.N) // 224 ms +} + +func BenchmarkBuffers(b *testing.B) { + // Adding buffers has no effect. + cakeshop := defaults + cakeshop.BakeBuf = 10 + cakeshop.IceBuf = 10 + cakeshop.Work(b.N) // 224 ms +} + +func BenchmarkVariable(b *testing.B) { + // Adding variability to rate of each step + // increases total time due to channel delays. + cakeshop := defaults + cakeshop.BakeStdDev = cakeshop.BakeTime / 4 + cakeshop.IceStdDev = cakeshop.IceTime / 4 + cakeshop.InscribeStdDev = cakeshop.InscribeTime / 4 + cakeshop.Work(b.N) // 259 ms +} + +func BenchmarkVariableBuffers(b *testing.B) { + // Adding channel buffers reduces + // delays resulting from variability. + cakeshop := defaults + cakeshop.BakeStdDev = cakeshop.BakeTime / 4 + cakeshop.IceStdDev = cakeshop.IceTime / 4 + cakeshop.InscribeStdDev = cakeshop.InscribeTime / 4 + cakeshop.BakeBuf = 10 + cakeshop.IceBuf = 10 + cakeshop.Work(b.N) // 244 ms +} + +func BenchmarkSlowIcing(b *testing.B) { + // Making the middle stage slower + // adds directly to the critical path. + cakeshop := defaults + cakeshop.IceTime = 50 * time.Millisecond + cakeshop.Work(b.N) // 1.032 s +} + +func BenchmarkSlowIcingManyIcers(b *testing.B) { + // Adding more icing cooks reduces the cost of icing + // to its sequential component, following Amdahl's Law. + cakeshop := defaults + cakeshop.IceTime = 50 * time.Millisecond + cakeshop.NumIcers = 5 + cakeshop.Work(b.N) // 288ms +} diff --git a/vendor/gopl.io/ch8/chat/chat.go b/vendor/gopl.io/ch8/chat/chat.go new file mode 100644 index 0000000..990bcf3 --- /dev/null +++ b/vendor/gopl.io/ch8/chat/chat.go @@ -0,0 +1,96 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 254. +//!+ + +// Chat is a server that lets clients chat with each other. +package main + +import ( + "bufio" + "fmt" + "log" + "net" +) + +//!+broadcaster +type client chan<- string // an outgoing message channel + +var ( + entering = make(chan client) + leaving = make(chan client) + messages = make(chan string) // all incoming client messages +) + +func broadcaster() { + clients := make(map[client]bool) // all connected clients + for { + select { + case msg := <-messages: + // Broadcast incoming message to all + // clients' outgoing message channels. + for cli := range clients { + cli <- msg + } + + case cli := <-entering: + clients[cli] = true + + case cli := <-leaving: + delete(clients, cli) + close(cli) + } + } +} + +//!-broadcaster + +//!+handleConn +func handleConn(conn net.Conn) { + ch := make(chan string) // outgoing client messages + go clientWriter(conn, ch) + + who := conn.RemoteAddr().String() + ch <- "You are " + who + messages <- who + " has arrived" + entering <- ch + + input := bufio.NewScanner(conn) + for input.Scan() { + messages <- who + ": " + input.Text() + } + // NOTE: ignoring potential errors from input.Err() + + leaving <- ch + messages <- who + " has left" + conn.Close() +} + +func clientWriter(conn net.Conn, ch <-chan string) { + for msg := range ch { + fmt.Fprintln(conn, msg) // NOTE: ignoring network errors + } +} + +//!-handleConn + +//!+main +func main() { + listener, err := net.Listen("tcp", "localhost:8000") + if err != nil { + log.Fatal(err) + } + + go broadcaster() + for { + conn, err := listener.Accept() + if err != nil { + log.Print(err) + continue + } + go handleConn(conn) + } +} + +//!-main diff --git a/vendor/gopl.io/ch8/chat/chat.go.~master~ b/vendor/gopl.io/ch8/chat/chat.go.~master~ new file mode 100644 index 0000000..225af17 --- /dev/null +++ b/vendor/gopl.io/ch8/chat/chat.go.~master~ @@ -0,0 +1,89 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +//!+ + +// Chat is a server that lets clients chat with each other. +package main + +import ( + "bufio" + "fmt" + "log" + "net" +) + +//!+broadcaster +type client chan<- string // an outgoing message channel + +var ( + entering = make(chan client) + leaving = make(chan client) + messages = make(chan string) // all incoming client messages +) + +func broadcaster() { + clients := make(map[client]bool) // all connected clients + for { + select { + case msg := <-messages: + // Broadcast incoming message to all + // clients' outgoing message channels. + for cli := range clients { + cli <- msg + } + case cli := <-entering: + clients[cli] = true + case cli := <-leaving: + delete(clients, cli) + close(cli) + } + } +} + +//!-broadcaster + +//!+handleConn +func handleConn(conn net.Conn) { + ch := make(chan string) // outgoing client messages + go clientWriter(conn, ch) + + who := conn.RemoteAddr().String() + entering <- ch + messages <- who + " has arrived" + input := bufio.NewScanner(conn) + for input.Scan() { + messages <- who + ": " + input.Text() + } + messages <- who + " has left" + leaving <- ch + conn.Close() +} + +func clientWriter(conn net.Conn, ch <-chan string) { + for msg := range ch { + fmt.Fprintln(conn, msg) + } +} + +//!-handleConn + +//!+main +func main() { + listener, err := net.Listen("tcp", "localhost:8000") + if err != nil { + log.Fatal(err) + } + + go broadcaster() + for { + conn, err := listener.Accept() + if err != nil { + log.Print(err) + continue + } + go handleConn(conn) + } +} + +//!-main diff --git a/vendor/gopl.io/ch8/clock1/clock.go b/vendor/gopl.io/ch8/clock1/clock.go new file mode 100644 index 0000000..03fada1 --- /dev/null +++ b/vendor/gopl.io/ch8/clock1/clock.go @@ -0,0 +1,43 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 219. +//!+ + +// Clock1 is a TCP server that periodically writes the time. +package main + +import ( + "io" + "log" + "net" + "time" +) + +func main() { + listener, err := net.Listen("tcp", "localhost:8000") + if err != nil { + log.Fatal(err) + } + for { + conn, err := listener.Accept() + if err != nil { + log.Print(err) // e.g., connection aborted + continue + } + handleConn(conn) // handle one connection at a time + } +} + +func handleConn(c net.Conn) { + defer c.Close() + for { + _, err := io.WriteString(c, time.Now().Format("15:04:05\n")) + if err != nil { + return // e.g., client disconnected + } + time.Sleep(1 * time.Second) + } +} + +//!- diff --git a/vendor/gopl.io/ch8/clock2/clock.go b/vendor/gopl.io/ch8/clock2/clock.go new file mode 100644 index 0000000..55c6235 --- /dev/null +++ b/vendor/gopl.io/ch8/clock2/clock.go @@ -0,0 +1,42 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 222. + +// Clock is a TCP server that periodically writes the time. +package main + +import ( + "io" + "log" + "net" + "time" +) + +func handleConn(c net.Conn) { + defer c.Close() + for { + _, err := io.WriteString(c, time.Now().Format("15:04:05\n")) + if err != nil { + return // e.g., client disconnected + } + time.Sleep(1 * time.Second) + } +} + +func main() { + listener, err := net.Listen("tcp", "localhost:8000") + if err != nil { + log.Fatal(err) + } + //!+ + for { + conn, err := listener.Accept() + if err != nil { + log.Print(err) // e.g., connection aborted + continue + } + go handleConn(conn) // handle connections concurrently + } + //!- +} diff --git a/vendor/gopl.io/ch8/countdown1/countdown.go b/vendor/gopl.io/ch8/countdown1/countdown.go new file mode 100644 index 0000000..036ba6a --- /dev/null +++ b/vendor/gopl.io/ch8/countdown1/countdown.go @@ -0,0 +1,29 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 244. + +// Countdown implements the countdown for a rocket launch. +package main + +import ( + "fmt" + "time" +) + +//!+ +func main() { + fmt.Println("Commencing countdown.") + tick := time.Tick(1 * time.Second) + for countdown := 10; countdown > 0; countdown-- { + fmt.Println(countdown) + <-tick + } + launch() +} + +//!- + +func launch() { + fmt.Println("Lift off!") +} diff --git a/vendor/gopl.io/ch8/countdown2/countdown.go b/vendor/gopl.io/ch8/countdown2/countdown.go new file mode 100644 index 0000000..6ac6746 --- /dev/null +++ b/vendor/gopl.io/ch8/countdown2/countdown.go @@ -0,0 +1,46 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 244. + +// Countdown implements the countdown for a rocket launch. +package main + +import ( + "fmt" + "os" + "time" +) + +//!+ + +func main() { + // ...create abort channel... + + //!- + + //!+abort + abort := make(chan struct{}) + go func() { + os.Stdin.Read(make([]byte, 1)) // read a single byte + abort <- struct{}{} + }() + //!-abort + + //!+ + fmt.Println("Commencing countdown. Press return to abort.") + select { + case <-time.After(10 * time.Second): + // Do nothing. + case <-abort: + fmt.Println("Launch aborted!") + return + } + launch() +} + +//!- + +func launch() { + fmt.Println("Lift off!") +} diff --git a/vendor/gopl.io/ch8/countdown3/countdown.go b/vendor/gopl.io/ch8/countdown3/countdown.go new file mode 100644 index 0000000..ade9a55 --- /dev/null +++ b/vendor/gopl.io/ch8/countdown3/countdown.go @@ -0,0 +1,51 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 246. + +// Countdown implements the countdown for a rocket launch. +package main + +// NOTE: the ticker goroutine never terminates if the launch is aborted. +// This is a "goroutine leak". + +import ( + "fmt" + "os" + "time" +) + +//!+ + +func main() { + // ...create abort channel... + + //!- + + abort := make(chan struct{}) + go func() { + os.Stdin.Read(make([]byte, 1)) // read a single byte + abort <- struct{}{} + }() + + //!+ + fmt.Println("Commencing countdown. Press return to abort.") + tick := time.Tick(1 * time.Second) + for countdown := 10; countdown > 0; countdown-- { + fmt.Println(countdown) + select { + case <-tick: + // Do nothing. + case <-abort: + fmt.Println("Launch aborted!") + return + } + } + launch() +} + +//!- + +func launch() { + fmt.Println("Lift off!") +} diff --git a/vendor/gopl.io/ch8/crawl1/findlinks.go b/vendor/gopl.io/ch8/crawl1/findlinks.go new file mode 100644 index 0000000..df568b4 --- /dev/null +++ b/vendor/gopl.io/ch8/crawl1/findlinks.go @@ -0,0 +1,72 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 240. + +// Crawl1 crawls web links starting with the command-line arguments. +// +// This version quickly exhausts available file descriptors +// due to excessive concurrent calls to links.Extract. +// +// Also, it never terminates because the worklist is never closed. +package main + +import ( + "fmt" + "log" + "os" + + "gopl.io/ch5/links" +) + +//!+crawl +func crawl(url string) []string { + fmt.Println(url) + list, err := links.Extract(url) + if err != nil { + log.Print(err) + } + return list +} + +//!-crawl + +//!+main +func main() { + worklist := make(chan []string) + + // Start with the command-line arguments. + go func() { worklist <- os.Args[1:] }() + + // Crawl the web concurrently. + seen := make(map[string]bool) + for list := range worklist { + for _, link := range list { + if !seen[link] { + seen[link] = true + go func(link string) { + worklist <- crawl(link) + }(link) + } + } + } +} + +//!-main + +/* +//!+output +$ go build gopl.io/ch8/crawl1 +$ ./crawl1 http://gopl.io/ +http://gopl.io/ +https://golang.org/help/ + +https://golang.org/doc/ +https://golang.org/blog/ +... +2015/07/15 18:22:12 Get ...: dial tcp: lookup blog.golang.org: no such host +2015/07/15 18:22:12 Get ...: dial tcp 23.21.222.120:443: socket: + too many open files +... +//!-output +*/ diff --git a/vendor/gopl.io/ch8/crawl2/findlinks.go b/vendor/gopl.io/ch8/crawl2/findlinks.go new file mode 100644 index 0000000..aad20f8 --- /dev/null +++ b/vendor/gopl.io/ch8/crawl2/findlinks.go @@ -0,0 +1,64 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 241. + +// Crawl2 crawls web links starting with the command-line arguments. +// +// This version uses a buffered channel as a counting semaphore +// to limit the number of concurrent calls to links.Extract. +package main + +import ( + "fmt" + "log" + "os" + + "gopl.io/ch5/links" +) + +//!+sema +// tokens is a counting semaphore used to +// enforce a limit of 20 concurrent requests. +var tokens = make(chan struct{}, 20) + +func crawl(url string) []string { + fmt.Println(url) + tokens <- struct{}{} // acquire a token + list, err := links.Extract(url) + <-tokens // release the token + + if err != nil { + log.Print(err) + } + return list +} + +//!-sema + +//!+ +func main() { + worklist := make(chan []string) + var n int // number of pending sends to worklist + + // Start with the command-line arguments. + n++ + go func() { worklist <- os.Args[1:] }() + + // Crawl the web concurrently. + seen := make(map[string]bool) + for ; n > 0; n-- { + list := <-worklist + for _, link := range list { + if !seen[link] { + seen[link] = true + n++ + go func(link string) { + worklist <- crawl(link) + }(link) + } + } + } +} + +//!- diff --git a/vendor/gopl.io/ch8/crawl3/findlinks.go b/vendor/gopl.io/ch8/crawl3/findlinks.go new file mode 100644 index 0000000..8283de1 --- /dev/null +++ b/vendor/gopl.io/ch8/crawl3/findlinks.go @@ -0,0 +1,61 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 243. + +// Crawl3 crawls web links starting with the command-line arguments. +// +// This version uses bounded parallelism. +// For simplicity, it does not address the termination problem. +// +package main + +import ( + "fmt" + "log" + "os" + + "gopl.io/ch5/links" +) + +func crawl(url string) []string { + fmt.Println(url) + list, err := links.Extract(url) + if err != nil { + log.Print(err) + } + return list +} + +//!+ +func main() { + worklist := make(chan []string) // lists of URLs, may have duplicates + unseenLinks := make(chan string) // de-duplicated URLs + + // Add command-line arguments to worklist. + go func() { worklist <- os.Args[1:] }() + + // Create 20 crawler goroutines to fetch each unseen link. + for i := 0; i < 20; i++ { + go func() { + for link := range unseenLinks { + foundLinks := crawl(link) + go func() { worklist <- foundLinks }() + } + }() + } + + // The main goroutine de-duplicates worklist items + // and sends the unseen ones to the crawlers. + seen := make(map[string]bool) + for list := range worklist { + for _, link := range list { + if !seen[link] { + seen[link] = true + unseenLinks <- link + } + } + } +} + +//!- diff --git a/vendor/gopl.io/ch8/du1/main.go b/vendor/gopl.io/ch8/du1/main.go new file mode 100644 index 0000000..8aee837 --- /dev/null +++ b/vendor/gopl.io/ch8/du1/main.go @@ -0,0 +1,79 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 247. + +//!+main + +// The du1 command computes the disk usage of the files in a directory. +package main + +import ( + "flag" + "fmt" + "io/ioutil" + "os" + "path/filepath" +) + +func main() { + // Determine the initial directories. + flag.Parse() + roots := flag.Args() + if len(roots) == 0 { + roots = []string{"."} + } + + // Traverse the file tree. + fileSizes := make(chan int64) + go func() { + for _, root := range roots { + walkDir(root, fileSizes) + } + close(fileSizes) + }() + + // Print the results. + var nfiles, nbytes int64 + for size := range fileSizes { + nfiles++ + nbytes += size + } + printDiskUsage(nfiles, nbytes) +} + +func printDiskUsage(nfiles, nbytes int64) { + fmt.Printf("%d files %.1f GB\n", nfiles, float64(nbytes)/1e9) +} + +//!-main + +//!+walkDir + +// walkDir recursively walks the file tree rooted at dir +// and sends the size of each found file on fileSizes. +func walkDir(dir string, fileSizes chan<- int64) { + for _, entry := range dirents(dir) { + if entry.IsDir() { + subdir := filepath.Join(dir, entry.Name()) + walkDir(subdir, fileSizes) + } else { + fileSizes <- entry.Size() + } + } +} + +// dirents returns the entries of directory dir. +func dirents(dir string) []os.FileInfo { + entries, err := ioutil.ReadDir(dir) + if err != nil { + fmt.Fprintf(os.Stderr, "du1: %v\n", err) + return nil + } + return entries +} + +//!-walkDir + +// The du1 variant uses two goroutines and +// prints the total after every file is found. diff --git a/vendor/gopl.io/ch8/du2/main.go b/vendor/gopl.io/ch8/du2/main.go new file mode 100644 index 0000000..842944f --- /dev/null +++ b/vendor/gopl.io/ch8/du2/main.go @@ -0,0 +1,94 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 249. + +// The du2 command computes the disk usage of the files in a directory. +package main + +// The du2 variant uses select and a time.Ticker +// to print the totals periodically if -v is set. + +import ( + "flag" + "fmt" + "io/ioutil" + "os" + "path/filepath" + "time" +) + +//!+ +var verbose = flag.Bool("v", false, "show verbose progress messages") + +func main() { + // ...start background goroutine... + + //!- + // Determine the initial directories. + flag.Parse() + roots := flag.Args() + if len(roots) == 0 { + roots = []string{"."} + } + + // Traverse the file tree. + fileSizes := make(chan int64) + go func() { + for _, root := range roots { + walkDir(root, fileSizes) + } + close(fileSizes) + }() + + //!+ + // Print the results periodically. + var tick <-chan time.Time + if *verbose { + tick = time.Tick(500 * time.Millisecond) + } + var nfiles, nbytes int64 +loop: + for { + select { + case size, ok := <-fileSizes: + if !ok { + break loop // fileSizes was closed + } + nfiles++ + nbytes += size + case <-tick: + printDiskUsage(nfiles, nbytes) + } + } + printDiskUsage(nfiles, nbytes) // final totals +} + +//!- + +func printDiskUsage(nfiles, nbytes int64) { + fmt.Printf("%d files %.1f GB\n", nfiles, float64(nbytes)/1e9) +} + +// walkDir recursively walks the file tree rooted at dir +// and sends the size of each found file on fileSizes. +func walkDir(dir string, fileSizes chan<- int64) { + for _, entry := range dirents(dir) { + if entry.IsDir() { + subdir := filepath.Join(dir, entry.Name()) + walkDir(subdir, fileSizes) + } else { + fileSizes <- entry.Size() + } + } +} + +// dirents returns the entries of directory dir. +func dirents(dir string) []os.FileInfo { + entries, err := ioutil.ReadDir(dir) + if err != nil { + fmt.Fprintf(os.Stderr, "du: %v\n", err) + return nil + } + return entries +} diff --git a/vendor/gopl.io/ch8/du3/main.go b/vendor/gopl.io/ch8/du3/main.go new file mode 100644 index 0000000..42b3214 --- /dev/null +++ b/vendor/gopl.io/ch8/du3/main.go @@ -0,0 +1,118 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 250. + +// The du3 command computes the disk usage of the files in a directory. +package main + +// The du3 variant traverses all directories in parallel. +// It uses a concurrency-limiting counting semaphore +// to avoid opening too many files at once. + +import ( + "flag" + "fmt" + "io/ioutil" + "os" + "path/filepath" + "sync" + "time" +) + +var vFlag = flag.Bool("v", false, "show verbose progress messages") + +//!+ +func main() { + // ...determine roots... + + //!- + flag.Parse() + + // Determine the initial directories. + roots := flag.Args() + if len(roots) == 0 { + roots = []string{"."} + } + + //!+ + // Traverse each root of the file tree in parallel. + fileSizes := make(chan int64) + var n sync.WaitGroup + for _, root := range roots { + n.Add(1) + go walkDir(root, &n, fileSizes) + } + go func() { + n.Wait() + close(fileSizes) + }() + //!- + + // Print the results periodically. + var tick <-chan time.Time + if *vFlag { + tick = time.Tick(500 * time.Millisecond) + } + var nfiles, nbytes int64 +loop: + for { + select { + case size, ok := <-fileSizes: + if !ok { + break loop // fileSizes was closed + } + nfiles++ + nbytes += size + case <-tick: + printDiskUsage(nfiles, nbytes) + } + } + + printDiskUsage(nfiles, nbytes) // final totals + //!+ + // ...select loop... +} + +//!- + +func printDiskUsage(nfiles, nbytes int64) { + fmt.Printf("%d files %.1f GB\n", nfiles, float64(nbytes)/1e9) +} + +// walkDir recursively walks the file tree rooted at dir +// and sends the size of each found file on fileSizes. +//!+walkDir +func walkDir(dir string, n *sync.WaitGroup, fileSizes chan<- int64) { + defer n.Done() + for _, entry := range dirents(dir) { + if entry.IsDir() { + n.Add(1) + subdir := filepath.Join(dir, entry.Name()) + go walkDir(subdir, n, fileSizes) + } else { + fileSizes <- entry.Size() + } + } +} + +//!-walkDir + +//!+sema +// sema is a counting semaphore for limiting concurrency in dirents. +var sema = make(chan struct{}, 20) + +// dirents returns the entries of directory dir. +func dirents(dir string) []os.FileInfo { + sema <- struct{}{} // acquire token + defer func() { <-sema }() // release token + // ... + //!-sema + + entries, err := ioutil.ReadDir(dir) + if err != nil { + fmt.Fprintf(os.Stderr, "du: %v\n", err) + return nil + } + return entries +} diff --git a/vendor/gopl.io/ch8/du4/main.go b/vendor/gopl.io/ch8/du4/main.go new file mode 100644 index 0000000..bc3f764 --- /dev/null +++ b/vendor/gopl.io/ch8/du4/main.go @@ -0,0 +1,145 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 251. + +// The du4 command computes the disk usage of the files in a directory. +package main + +// The du4 variant includes cancellation: +// it terminates quickly when the user hits return. + +import ( + "fmt" + "os" + "path/filepath" + "sync" + "time" +) + +//!+1 +var done = make(chan struct{}) + +func cancelled() bool { + select { + case <-done: + return true + default: + return false + } +} + +//!-1 + +func main() { + // Determine the initial directories. + roots := os.Args[1:] + if len(roots) == 0 { + roots = []string{"."} + } + + //!+2 + // Cancel traversal when input is detected. + go func() { + os.Stdin.Read(make([]byte, 1)) // read a single byte + close(done) + }() + //!-2 + + // Traverse each root of the file tree in parallel. + fileSizes := make(chan int64) + var n sync.WaitGroup + for _, root := range roots { + n.Add(1) + go walkDir(root, &n, fileSizes) + } + go func() { + n.Wait() + close(fileSizes) + }() + + // Print the results periodically. + tick := time.Tick(500 * time.Millisecond) + var nfiles, nbytes int64 +loop: + //!+3 + for { + select { + case <-done: + // Drain fileSizes to allow existing goroutines to finish. + for range fileSizes { + // Do nothing. + } + return + case size, ok := <-fileSizes: + // ... + //!-3 + if !ok { + break loop // fileSizes was closed + } + nfiles++ + nbytes += size + case <-tick: + printDiskUsage(nfiles, nbytes) + } + } + printDiskUsage(nfiles, nbytes) // final totals +} + +func printDiskUsage(nfiles, nbytes int64) { + fmt.Printf("%d files %.1f GB\n", nfiles, float64(nbytes)/1e9) +} + +// walkDir recursively walks the file tree rooted at dir +// and sends the size of each found file on fileSizes. +//!+4 +func walkDir(dir string, n *sync.WaitGroup, fileSizes chan<- int64) { + defer n.Done() + if cancelled() { + return + } + for _, entry := range dirents(dir) { + // ... + //!-4 + if entry.IsDir() { + n.Add(1) + subdir := filepath.Join(dir, entry.Name()) + go walkDir(subdir, n, fileSizes) + } else { + fileSizes <- entry.Size() + } + //!+4 + } +} + +//!-4 + +var sema = make(chan struct{}, 20) // concurrency-limiting counting semaphore + +// dirents returns the entries of directory dir. +//!+5 +func dirents(dir string) []os.FileInfo { + select { + case sema <- struct{}{}: // acquire token + case <-done: + return nil // cancelled + } + defer func() { <-sema }() // release token + + // ...read directory... + //!-5 + + f, err := os.Open(dir) + if err != nil { + fmt.Fprintf(os.Stderr, "du: %v\n", err) + return nil + } + defer f.Close() + + entries, err := f.Readdir(0) // 0 => no limit; read all entries + if err != nil { + fmt.Fprintf(os.Stderr, "du: %v\n", err) + // Don't return: Readdir may return partial results. + } + return entries +} diff --git a/vendor/gopl.io/ch8/netcat1/netcat.go b/vendor/gopl.io/ch8/netcat1/netcat.go new file mode 100644 index 0000000..e3c7823 --- /dev/null +++ b/vendor/gopl.io/ch8/netcat1/netcat.go @@ -0,0 +1,32 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 221. +//!+ + +// Netcat1 is a read-only TCP client. +package main + +import ( + "io" + "log" + "net" + "os" +) + +func main() { + conn, err := net.Dial("tcp", "localhost:8000") + if err != nil { + log.Fatal(err) + } + defer conn.Close() + mustCopy(os.Stdout, conn) +} + +func mustCopy(dst io.Writer, src io.Reader) { + if _, err := io.Copy(dst, src); err != nil { + log.Fatal(err) + } +} + +//!- diff --git a/vendor/gopl.io/ch8/netcat2/netcat.go b/vendor/gopl.io/ch8/netcat2/netcat.go new file mode 100644 index 0000000..7a86a5c --- /dev/null +++ b/vendor/gopl.io/ch8/netcat2/netcat.go @@ -0,0 +1,33 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 223. + +// Netcat is a simple read/write client for TCP servers. +package main + +import ( + "io" + "log" + "net" + "os" +) + +//!+ +func main() { + conn, err := net.Dial("tcp", "localhost:8000") + if err != nil { + log.Fatal(err) + } + defer conn.Close() + go mustCopy(os.Stdout, conn) + mustCopy(conn, os.Stdin) +} + +//!- + +func mustCopy(dst io.Writer, src io.Reader) { + if _, err := io.Copy(dst, src); err != nil { + log.Fatal(err) + } +} diff --git a/vendor/gopl.io/ch8/netcat3/netcat.go b/vendor/gopl.io/ch8/netcat3/netcat.go new file mode 100644 index 0000000..3950998 --- /dev/null +++ b/vendor/gopl.io/ch8/netcat3/netcat.go @@ -0,0 +1,39 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 227. + +// Netcat is a simple read/write client for TCP servers. +package main + +import ( + "io" + "log" + "net" + "os" +) + +//!+ +func main() { + conn, err := net.Dial("tcp", "localhost:8000") + if err != nil { + log.Fatal(err) + } + done := make(chan struct{}) + go func() { + io.Copy(os.Stdout, conn) // NOTE: ignoring errors + log.Println("done") + done <- struct{}{} // signal the main goroutine + }() + mustCopy(conn, os.Stdin) + conn.Close() + <-done // wait for background goroutine to finish +} + +//!- + +func mustCopy(dst io.Writer, src io.Reader) { + if _, err := io.Copy(dst, src); err != nil { + log.Fatal(err) + } +} diff --git a/vendor/gopl.io/ch8/pipeline1/main.go b/vendor/gopl.io/ch8/pipeline1/main.go new file mode 100644 index 0000000..06ecd5c --- /dev/null +++ b/vendor/gopl.io/ch8/pipeline1/main.go @@ -0,0 +1,37 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 228. + +// Pipeline1 demonstrates an infinite 3-stage pipeline. +package main + +import "fmt" + +//!+ +func main() { + naturals := make(chan int) + squares := make(chan int) + + // Counter + go func() { + for x := 0; ; x++ { + naturals <- x + } + }() + + // Squarer + go func() { + for { + x := <-naturals + squares <- x * x + } + }() + + // Printer (in main goroutine) + for { + fmt.Println(<-squares) + } +} + +//!- diff --git a/vendor/gopl.io/ch8/pipeline2/main.go b/vendor/gopl.io/ch8/pipeline2/main.go new file mode 100644 index 0000000..6015c01 --- /dev/null +++ b/vendor/gopl.io/ch8/pipeline2/main.go @@ -0,0 +1,38 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 229. + +// Pipeline2 demonstrates a finite 3-stage pipeline. +package main + +import "fmt" + +//!+ +func main() { + naturals := make(chan int) + squares := make(chan int) + + // Counter + go func() { + for x := 0; x < 100; x++ { + naturals <- x + } + close(naturals) + }() + + // Squarer + go func() { + for x := range naturals { + squares <- x * x + } + close(squares) + }() + + // Printer (in main goroutine) + for x := range squares { + fmt.Println(x) + } +} + +//!- diff --git a/vendor/gopl.io/ch8/pipeline3/main.go b/vendor/gopl.io/ch8/pipeline3/main.go new file mode 100644 index 0000000..cc679ea --- /dev/null +++ b/vendor/gopl.io/ch8/pipeline3/main.go @@ -0,0 +1,42 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 231. + +// Pipeline3 demonstrates a finite 3-stage pipeline +// with range, close, and unidirectional channel types. +package main + +import "fmt" + +//!+ +func counter(out chan<- int) { + for x := 0; x < 100; x++ { + out <- x + } + close(out) +} + +func squarer(out chan<- int, in <-chan int) { + for v := range in { + out <- v * v + } + close(out) +} + +func printer(in <-chan int) { + for v := range in { + fmt.Println(v) + } +} + +func main() { + naturals := make(chan int) + squares := make(chan int) + + go counter(naturals) + go squarer(squares, naturals) + printer(squares) +} + +//!- diff --git a/vendor/gopl.io/ch8/reverb1/reverb.go b/vendor/gopl.io/ch8/reverb1/reverb.go new file mode 100644 index 0000000..c72823f --- /dev/null +++ b/vendor/gopl.io/ch8/reverb1/reverb.go @@ -0,0 +1,51 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 223. + +// Reverb1 is a TCP server that simulates an echo. +package main + +import ( + "bufio" + "fmt" + "log" + "net" + "strings" + "time" +) + +//!+ +func echo(c net.Conn, shout string, delay time.Duration) { + fmt.Fprintln(c, "\t", strings.ToUpper(shout)) + time.Sleep(delay) + fmt.Fprintln(c, "\t", shout) + time.Sleep(delay) + fmt.Fprintln(c, "\t", strings.ToLower(shout)) +} + +func handleConn(c net.Conn) { + input := bufio.NewScanner(c) + for input.Scan() { + echo(c, input.Text(), 1*time.Second) + } + // NOTE: ignoring potential errors from input.Err() + c.Close() +} + +//!- + +func main() { + l, err := net.Listen("tcp", "localhost:8000") + if err != nil { + log.Fatal(err) + } + for { + conn, err := l.Accept() + if err != nil { + log.Print(err) // e.g., connection aborted + continue + } + go handleConn(conn) + } +} diff --git a/vendor/gopl.io/ch8/reverb2/reverb.go b/vendor/gopl.io/ch8/reverb2/reverb.go new file mode 100644 index 0000000..b74487d --- /dev/null +++ b/vendor/gopl.io/ch8/reverb2/reverb.go @@ -0,0 +1,51 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 224. + +// Reverb2 is a TCP server that simulates an echo. +package main + +import ( + "bufio" + "fmt" + "log" + "net" + "strings" + "time" +) + +func echo(c net.Conn, shout string, delay time.Duration) { + fmt.Fprintln(c, "\t", strings.ToUpper(shout)) + time.Sleep(delay) + fmt.Fprintln(c, "\t", shout) + time.Sleep(delay) + fmt.Fprintln(c, "\t", strings.ToLower(shout)) +} + +//!+ +func handleConn(c net.Conn) { + input := bufio.NewScanner(c) + for input.Scan() { + go echo(c, input.Text(), 1*time.Second) + } + // NOTE: ignoring potential errors from input.Err() + c.Close() +} + +//!- + +func main() { + l, err := net.Listen("tcp", "localhost:8000") + if err != nil { + log.Fatal(err) + } + for { + conn, err := l.Accept() + if err != nil { + log.Print(err) // e.g., connection aborted + continue + } + go handleConn(conn) + } +} diff --git a/vendor/gopl.io/ch8/spinner/main.go b/vendor/gopl.io/ch8/spinner/main.go new file mode 100644 index 0000000..c6a8cb1 --- /dev/null +++ b/vendor/gopl.io/ch8/spinner/main.go @@ -0,0 +1,38 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 218. + +// Spinner displays an animation while computing the 45th Fibonacci number. +package main + +import ( + "fmt" + "time" +) + +//!+ +func main() { + go spinner(100 * time.Millisecond) + const n = 45 + fibN := fib(n) // slow + fmt.Printf("\rFibonacci(%d) = %d\n", n, fibN) +} + +func spinner(delay time.Duration) { + for { + for _, r := range `-\|/` { + fmt.Printf("\r%c", r) + time.Sleep(delay) + } + } +} + +func fib(x int) int { + if x < 2 { + return x + } + return fib(x-1) + fib(x-2) +} + +//!- diff --git a/vendor/gopl.io/ch8/thumbnail/main.go b/vendor/gopl.io/ch8/thumbnail/main.go new file mode 100644 index 0000000..a66174c --- /dev/null +++ b/vendor/gopl.io/ch8/thumbnail/main.go @@ -0,0 +1,42 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// +build ignore + +// The thumbnail command produces thumbnails of JPEG files +// whose names are provided on each line of the standard input. +// +// The "+build ignore" tag (see p.295) excludes this file from the +// thumbnail package, but it can be compiled as a command and run like +// this: +// +// Run with: +// $ go run $GOPATH/src/gopl.io/ch8/thumbnail/main.go +// foo.jpeg +// ^D +// +package main + +import ( + "bufio" + "fmt" + "log" + "os" + + "gopl.io/ch8/thumbnail" +) + +func main() { + input := bufio.NewScanner(os.Stdin) + for input.Scan() { + thumb, err := thumbnail.ImageFile(input.Text()) + if err != nil { + log.Print(err) + continue + } + fmt.Println(thumb) + } + if err := input.Err(); err != nil { + log.Fatal(err) + } +} diff --git a/vendor/gopl.io/ch8/thumbnail/thumbnail.go b/vendor/gopl.io/ch8/thumbnail/thumbnail.go new file mode 100644 index 0000000..a05f702 --- /dev/null +++ b/vendor/gopl.io/ch8/thumbnail/thumbnail.go @@ -0,0 +1,86 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 234. + +// The thumbnail package produces thumbnail-size images from +// larger images. Only JPEG images are currently supported. +package thumbnail + +import ( + "fmt" + "image" + "image/jpeg" + "io" + "os" + "path/filepath" + "strings" +) + +// Image returns a thumbnail-size version of src. +func Image(src image.Image) image.Image { + // Compute thumbnail size, preserving aspect ratio. + xs := src.Bounds().Size().X + ys := src.Bounds().Size().Y + width, height := 128, 128 + if aspect := float64(xs) / float64(ys); aspect < 1.0 { + width = int(128 * aspect) // portrait + } else { + height = int(128 / aspect) // landscape + } + xscale := float64(xs) / float64(width) + yscale := float64(ys) / float64(height) + + dst := image.NewRGBA(image.Rect(0, 0, width, height)) + + // a very crude scaling algorithm + for x := 0; x < width; x++ { + for y := 0; y < height; y++ { + srcx := int(float64(x) * xscale) + srcy := int(float64(y) * yscale) + dst.Set(x, y, src.At(srcx, srcy)) + } + } + return dst +} + +// ImageStream reads an image from r and +// writes a thumbnail-size version of it to w. +func ImageStream(w io.Writer, r io.Reader) error { + src, _, err := image.Decode(r) + if err != nil { + return err + } + dst := Image(src) + return jpeg.Encode(w, dst, nil) +} + +// ImageFile2 reads an image from infile and writes +// a thumbnail-size version of it to outfile. +func ImageFile2(outfile, infile string) (err error) { + in, err := os.Open(infile) + if err != nil { + return err + } + defer in.Close() + + out, err := os.Create(outfile) + if err != nil { + return err + } + + if err := ImageStream(out, in); err != nil { + out.Close() + return fmt.Errorf("scaling %s to %s: %s", infile, outfile, err) + } + return out.Close() +} + +// ImageFile reads an image from infile and writes +// a thumbnail-size version of it in the same directory. +// It returns the generated file name, e.g. "foo.thumb.jpeg". +func ImageFile(infile string) (string, error) { + ext := filepath.Ext(infile) // e.g., ".jpg", ".JPEG" + outfile := strings.TrimSuffix(infile, ext) + ".thumb" + ext + return outfile, ImageFile2(outfile, infile) +} diff --git a/vendor/gopl.io/ch8/thumbnail/thumbnail_test.go b/vendor/gopl.io/ch8/thumbnail/thumbnail_test.go new file mode 100644 index 0000000..be05b6c --- /dev/null +++ b/vendor/gopl.io/ch8/thumbnail/thumbnail_test.go @@ -0,0 +1,148 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// This file is just a place to put example code from the book. +// It does not actually run any code in gopl.io/ch8/thumbnail. + +package thumbnail_test + +import ( + "log" + "os" + "sync" + + "gopl.io/ch8/thumbnail" +) + +//!+1 +// makeThumbnails makes thumbnails of the specified files. +func makeThumbnails(filenames []string) { + for _, f := range filenames { + if _, err := thumbnail.ImageFile(f); err != nil { + log.Println(err) + } + } +} + +//!-1 + +//!+2 +// NOTE: incorrect! +func makeThumbnails2(filenames []string) { + for _, f := range filenames { + go thumbnail.ImageFile(f) // NOTE: ignoring errors + } +} + +//!-2 + +//!+3 +// makeThumbnails3 makes thumbnails of the specified files in parallel. +func makeThumbnails3(filenames []string) { + ch := make(chan struct{}) + for _, f := range filenames { + go func(f string) { + thumbnail.ImageFile(f) // NOTE: ignoring errors + ch <- struct{}{} + }(f) + } + + // Wait for goroutines to complete. + for range filenames { + <-ch + } +} + +//!-3 + +//!+4 +// makeThumbnails4 makes thumbnails for the specified files in parallel. +// It returns an error if any step failed. +func makeThumbnails4(filenames []string) error { + errors := make(chan error) + + for _, f := range filenames { + go func(f string) { + _, err := thumbnail.ImageFile(f) + errors <- err + }(f) + } + + for range filenames { + if err := <-errors; err != nil { + return err // NOTE: incorrect: goroutine leak! + } + } + + return nil +} + +//!-4 + +//!+5 +// makeThumbnails5 makes thumbnails for the specified files in parallel. +// It returns the generated file names in an arbitrary order, +// or an error if any step failed. +func makeThumbnails5(filenames []string) (thumbfiles []string, err error) { + type item struct { + thumbfile string + err error + } + + ch := make(chan item, len(filenames)) + for _, f := range filenames { + go func(f string) { + var it item + it.thumbfile, it.err = thumbnail.ImageFile(f) + ch <- it + }(f) + } + + for range filenames { + it := <-ch + if it.err != nil { + return nil, it.err + } + thumbfiles = append(thumbfiles, it.thumbfile) + } + + return thumbfiles, nil +} + +//!-5 + +//!+6 +// makeThumbnails6 makes thumbnails for each file received from the channel. +// It returns the number of bytes occupied by the files it creates. +func makeThumbnails6(filenames <-chan string) int64 { + sizes := make(chan int64) + var wg sync.WaitGroup // number of working goroutines + for f := range filenames { + wg.Add(1) + // worker + go func(f string) { + defer wg.Done() + thumb, err := thumbnail.ImageFile(f) + if err != nil { + log.Println(err) + return + } + info, _ := os.Stat(thumb) // OK to ignore error + sizes <- info.Size() + }(f) + } + + // closer + go func() { + wg.Wait() + close(sizes) + }() + + var total int64 + for size := range sizes { + total += size + } + return total +} + +//!-6 diff --git a/vendor/gopl.io/ch9/bank1/bank.go b/vendor/gopl.io/ch9/bank1/bank.go new file mode 100644 index 0000000..67fb41a --- /dev/null +++ b/vendor/gopl.io/ch9/bank1/bank.go @@ -0,0 +1,31 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 261. +//!+ + +// Package bank provides a concurrency-safe bank with one account. +package bank + +var deposits = make(chan int) // send amount to deposit +var balances = make(chan int) // receive balance + +func Deposit(amount int) { deposits <- amount } +func Balance() int { return <-balances } + +func teller() { + var balance int // balance is confined to teller goroutine + for { + select { + case amount := <-deposits: + balance += amount + case balances <- balance: + } + } +} + +func init() { + go teller() // start the monitor goroutine +} + +//!- diff --git a/vendor/gopl.io/ch9/bank1/bank_test.go b/vendor/gopl.io/ch9/bank1/bank_test.go new file mode 100644 index 0000000..1c36b1c --- /dev/null +++ b/vendor/gopl.io/ch9/bank1/bank_test.go @@ -0,0 +1,36 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package bank_test + +import ( + "fmt" + "testing" + + "gopl.io/ch9/bank1" +) + +func TestBank(t *testing.T) { + done := make(chan struct{}) + + // Alice + go func() { + bank.Deposit(200) + fmt.Println("=", bank.Balance()) + done <- struct{}{} + }() + + // Bob + go func() { + bank.Deposit(100) + done <- struct{}{} + }() + + // Wait for both transactions. + <-done + <-done + + if got, want := bank.Balance(), 300; got != want { + t.Errorf("Balance = %d, want %d", got, want) + } +} diff --git a/vendor/gopl.io/ch9/bank2/bank.go b/vendor/gopl.io/ch9/bank2/bank.go new file mode 100644 index 0000000..8cc73d7 --- /dev/null +++ b/vendor/gopl.io/ch9/bank2/bank.go @@ -0,0 +1,28 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 262. + +// Package bank provides a concurrency-safe bank with one account. +package bank + +//!+ +var ( + sema = make(chan struct{}, 1) // a binary semaphore guarding balance + balance int +) + +func Deposit(amount int) { + sema <- struct{}{} // acquire token + balance = balance + amount + <-sema // release token +} + +func Balance() int { + sema <- struct{}{} // acquire token + b := balance + <-sema // release token + return b +} + +//!- diff --git a/vendor/gopl.io/ch9/bank2/bank_test.go b/vendor/gopl.io/ch9/bank2/bank_test.go new file mode 100644 index 0000000..98fed00 --- /dev/null +++ b/vendor/gopl.io/ch9/bank2/bank_test.go @@ -0,0 +1,28 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package bank_test + +import ( + "sync" + "testing" + + "gopl.io/ch9/bank2" +) + +func TestBank(t *testing.T) { + // Deposit [1..1000] concurrently. + var n sync.WaitGroup + for i := 1; i <= 1000; i++ { + n.Add(1) + go func(amount int) { + bank.Deposit(amount) + n.Done() + }(i) + } + n.Wait() + + if got, want := bank.Balance(), (1000+1)*1000/2; got != want { + t.Errorf("Balance = %d, want %d", got, want) + } +} diff --git a/vendor/gopl.io/ch9/bank3/bank.go b/vendor/gopl.io/ch9/bank3/bank.go new file mode 100644 index 0000000..5c42d45 --- /dev/null +++ b/vendor/gopl.io/ch9/bank3/bank.go @@ -0,0 +1,30 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 263. + +// Package bank provides a concurrency-safe single-account bank. +package bank + +//!+ +import "sync" + +var ( + mu sync.Mutex // guards balance + balance int +) + +func Deposit(amount int) { + mu.Lock() + balance = balance + amount + mu.Unlock() +} + +func Balance() int { + mu.Lock() + b := balance + mu.Unlock() + return b +} + +//!- diff --git a/vendor/gopl.io/ch9/bank3/bank_test.go b/vendor/gopl.io/ch9/bank3/bank_test.go new file mode 100644 index 0000000..98fed00 --- /dev/null +++ b/vendor/gopl.io/ch9/bank3/bank_test.go @@ -0,0 +1,28 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package bank_test + +import ( + "sync" + "testing" + + "gopl.io/ch9/bank2" +) + +func TestBank(t *testing.T) { + // Deposit [1..1000] concurrently. + var n sync.WaitGroup + for i := 1; i <= 1000; i++ { + n.Add(1) + go func(amount int) { + bank.Deposit(amount) + n.Done() + }(i) + } + n.Wait() + + if got, want := bank.Balance(), (1000+1)*1000/2; got != want { + t.Errorf("Balance = %d, want %d", got, want) + } +} diff --git a/vendor/gopl.io/ch9/memo1/memo.go b/vendor/gopl.io/ch9/memo1/memo.go new file mode 100644 index 0000000..7b9c1b6 --- /dev/null +++ b/vendor/gopl.io/ch9/memo1/memo.go @@ -0,0 +1,40 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 272. + +//!+ + +// Package memo provides a concurrency-unsafe +// memoization of a function of type Func. +package memo + +// A Memo caches the results of calling a Func. +type Memo struct { + f Func + cache map[string]result +} + +// Func is the type of the function to memoize. +type Func func(key string) (interface{}, error) + +type result struct { + value interface{} + err error +} + +func New(f Func) *Memo { + return &Memo{f: f, cache: make(map[string]result)} +} + +// NOTE: not concurrency-safe! +func (memo *Memo) Get(key string) (interface{}, error) { + res, ok := memo.cache[key] + if !ok { + res.value, res.err = memo.f(key) + memo.cache[key] = res + } + return res.value, res.err +} + +//!- diff --git a/vendor/gopl.io/ch9/memo1/memo_test.go b/vendor/gopl.io/ch9/memo1/memo_test.go new file mode 100644 index 0000000..1b1c9af --- /dev/null +++ b/vendor/gopl.io/ch9/memo1/memo_test.go @@ -0,0 +1,67 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package memo_test + +import ( + "testing" + + "gopl.io/ch9/memo1" + "gopl.io/ch9/memotest" +) + +var httpGetBody = memotest.HTTPGetBody + +func Test(t *testing.T) { + m := memo.New(httpGetBody) + memotest.Sequential(t, m) +} + +// NOTE: not concurrency-safe! Test fails. +func TestConcurrent(t *testing.T) { + m := memo.New(httpGetBody) + memotest.Concurrent(t, m) +} + +/* +//!+output +$ go test -v gopl.io/ch9/memo1 +=== RUN Test +https://golang.org, 175.026418ms, 7537 bytes +https://godoc.org, 172.686825ms, 6878 bytes +https://play.golang.org, 115.762377ms, 5767 bytes +http://gopl.io, 749.887242ms, 2856 bytes + +https://golang.org, 721ns, 7537 bytes +https://godoc.org, 152ns, 6878 bytes +https://play.golang.org, 205ns, 5767 bytes +http://gopl.io, 326ns, 2856 bytes +--- PASS: Test (1.21s) +PASS +ok gopl.io/ch9/memo1 1.257s +//!-output +*/ + +/* +//!+race +$ go test -run=TestConcurrent -race -v gopl.io/ch9/memo1 +=== RUN TestConcurrent +... +WARNING: DATA RACE +Write by goroutine 36: + runtime.mapassign1() + ~/go/src/runtime/hashmap.go:411 +0x0 + gopl.io/ch9/memo1.(*Memo).Get() + ~/gobook2/src/gopl.io/ch9/memo1/memo.go:32 +0x205 + ... + +Previous write by goroutine 35: + runtime.mapassign1() + ~/go/src/runtime/hashmap.go:411 +0x0 + gopl.io/ch9/memo1.(*Memo).Get() + ~/gobook2/src/gopl.io/ch9/memo1/memo.go:32 +0x205 +... +Found 1 data race(s) +FAIL gopl.io/ch9/memo1 2.393s +//!-race +*/ diff --git a/vendor/gopl.io/ch9/memo2/memo.go b/vendor/gopl.io/ch9/memo2/memo.go new file mode 100644 index 0000000..6397c1a --- /dev/null +++ b/vendor/gopl.io/ch9/memo2/memo.go @@ -0,0 +1,44 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 275. + +// Package memo provides a concurrency-safe memoization a function of +// type Func. Concurrent requests are serialized by a Mutex. +package memo + +import "sync" + +// Func is the type of the function to memoize. +type Func func(string) (interface{}, error) + +type result struct { + value interface{} + err error +} + +func New(f Func) *Memo { + return &Memo{f: f, cache: make(map[string]result)} +} + +//!+ + +type Memo struct { + f Func + mu sync.Mutex // guards cache + cache map[string]result +} + +// Get is concurrency-safe. +func (memo *Memo) Get(key string) (value interface{}, err error) { + memo.mu.Lock() + res, ok := memo.cache[key] + if !ok { + res.value, res.err = memo.f(key) + memo.cache[key] = res + } + memo.mu.Unlock() + return res.value, res.err +} + +//!- diff --git a/vendor/gopl.io/ch9/memo2/memo_test.go b/vendor/gopl.io/ch9/memo2/memo_test.go new file mode 100644 index 0000000..bd4dc7b --- /dev/null +++ b/vendor/gopl.io/ch9/memo2/memo_test.go @@ -0,0 +1,23 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package memo_test + +import ( + "testing" + + "gopl.io/ch9/memo2" + "gopl.io/ch9/memotest" +) + +var httpGetBody = memotest.HTTPGetBody + +func Test(t *testing.T) { + m := memo.New(httpGetBody) + memotest.Sequential(t, m) +} + +func TestConcurrent(t *testing.T) { + m := memo.New(httpGetBody) + memotest.Concurrent(t, m) +} diff --git a/vendor/gopl.io/ch9/memo3/memo.go b/vendor/gopl.io/ch9/memo3/memo.go new file mode 100644 index 0000000..0c21afe --- /dev/null +++ b/vendor/gopl.io/ch9/memo3/memo.go @@ -0,0 +1,48 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 276. + +// Package memo provides a concurrency-safe memoization a function of +// type Func. Requests for different keys run concurrently. +// Concurrent requests for the same key result in duplicate work. +package memo + +import "sync" + +type Memo struct { + f Func + mu sync.Mutex // guards cache + cache map[string]result +} + +type Func func(string) (interface{}, error) + +type result struct { + value interface{} + err error +} + +func New(f Func) *Memo { + return &Memo{f: f, cache: make(map[string]result)} +} + +//!+ + +func (memo *Memo) Get(key string) (value interface{}, err error) { + memo.mu.Lock() + res, ok := memo.cache[key] + memo.mu.Unlock() + if !ok { + res.value, res.err = memo.f(key) + + // Between the two critical sections, several goroutines + // may race to compute f(key) and update the map. + memo.mu.Lock() + memo.cache[key] = res + memo.mu.Unlock() + } + return res.value, res.err +} + +//!- diff --git a/vendor/gopl.io/ch9/memo3/memo_test.go b/vendor/gopl.io/ch9/memo3/memo_test.go new file mode 100644 index 0000000..19fc5f0 --- /dev/null +++ b/vendor/gopl.io/ch9/memo3/memo_test.go @@ -0,0 +1,23 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package memo_test + +import ( + "testing" + + "gopl.io/ch9/memo3" + "gopl.io/ch9/memotest" +) + +var httpGetBody = memotest.HTTPGetBody + +func Test(t *testing.T) { + m := memo.New(httpGetBody) + memotest.Sequential(t, m) +} + +func TestConcurrent(t *testing.T) { + m := memo.New(httpGetBody) + memotest.Concurrent(t, m) +} diff --git a/vendor/gopl.io/ch9/memo4/memo.go b/vendor/gopl.io/ch9/memo4/memo.go new file mode 100644 index 0000000..fc70e2f --- /dev/null +++ b/vendor/gopl.io/ch9/memo4/memo.go @@ -0,0 +1,61 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 276. + +// Package memo provides a concurrency-safe memoization a function of +// a function. Requests for different keys proceed in parallel. +// Concurrent requests for the same key block until the first completes. +// This implementation uses a Mutex. +package memo + +import "sync" + +// Func is the type of the function to memoize. +type Func func(string) (interface{}, error) + +type result struct { + value interface{} + err error +} + +//!+ +type entry struct { + res result + ready chan struct{} // closed when res is ready +} + +func New(f Func) *Memo { + return &Memo{f: f, cache: make(map[string]*entry)} +} + +type Memo struct { + f Func + mu sync.Mutex // guards cache + cache map[string]*entry +} + +func (memo *Memo) Get(key string) (value interface{}, err error) { + memo.mu.Lock() + e := memo.cache[key] + if e == nil { + // This is the first request for this key. + // This goroutine becomes responsible for computing + // the value and broadcasting the ready condition. + e = &entry{ready: make(chan struct{})} + memo.cache[key] = e + memo.mu.Unlock() + + e.res.value, e.res.err = memo.f(key) + + close(e.ready) // broadcast ready condition + } else { + // This is a repeat request for this key. + memo.mu.Unlock() + + <-e.ready // wait for ready condition + } + return e.res.value, e.res.err +} + +//!- diff --git a/vendor/gopl.io/ch9/memo4/memo_test.go b/vendor/gopl.io/ch9/memo4/memo_test.go new file mode 100644 index 0000000..55cdc12 --- /dev/null +++ b/vendor/gopl.io/ch9/memo4/memo_test.go @@ -0,0 +1,23 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package memo_test + +import ( + "testing" + + "gopl.io/ch9/memo4" + "gopl.io/ch9/memotest" +) + +var httpGetBody = memotest.HTTPGetBody + +func Test(t *testing.T) { + m := memo.New(httpGetBody) + memotest.Sequential(t, m) +} + +func TestConcurrent(t *testing.T) { + m := memo.New(httpGetBody) + memotest.Concurrent(t, m) +} diff --git a/vendor/gopl.io/ch9/memo5/memo.go b/vendor/gopl.io/ch9/memo5/memo.go new file mode 100644 index 0000000..4a8fd9b --- /dev/null +++ b/vendor/gopl.io/ch9/memo5/memo.go @@ -0,0 +1,88 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 278. + +// Package memo provides a concurrency-safe non-blocking memoization +// of a function. Requests for different keys proceed in parallel. +// Concurrent requests for the same key block until the first completes. +// This implementation uses a monitor goroutine. +package memo + +//!+Func + +// Func is the type of the function to memoize. +type Func func(key string) (interface{}, error) + +// A result is the result of calling a Func. +type result struct { + value interface{} + err error +} + +type entry struct { + res result + ready chan struct{} // closed when res is ready +} + +//!-Func + +//!+get + +// A request is a message requesting that the Func be applied to key. +type request struct { + key string + response chan<- result // the client wants a single result +} + +type Memo struct{ requests chan request } + +// New returns a memoization of f. Clients must subsequently call Close. +func New(f Func) *Memo { + memo := &Memo{requests: make(chan request)} + go memo.server(f) + return memo +} + +func (memo *Memo) Get(key string) (interface{}, error) { + response := make(chan result) + memo.requests <- request{key, response} + res := <-response + return res.value, res.err +} + +func (memo *Memo) Close() { close(memo.requests) } + +//!-get + +//!+monitor + +func (memo *Memo) server(f Func) { + cache := make(map[string]*entry) + for req := range memo.requests { + e := cache[req.key] + if e == nil { + // This is the first request for this key. + e = &entry{ready: make(chan struct{})} + cache[req.key] = e + go e.call(f, req.key) // call f(key) + } + go e.deliver(req.response) + } +} + +func (e *entry) call(f Func, key string) { + // Evaluate the function. + e.res.value, e.res.err = f(key) + // Broadcast the ready condition. + close(e.ready) +} + +func (e *entry) deliver(response chan<- result) { + // Wait for the ready condition. + <-e.ready + // Send the result to the client. + response <- e.res +} + +//!-monitor diff --git a/vendor/gopl.io/ch9/memo5/memo_test.go b/vendor/gopl.io/ch9/memo5/memo_test.go new file mode 100644 index 0000000..e74052e --- /dev/null +++ b/vendor/gopl.io/ch9/memo5/memo_test.go @@ -0,0 +1,25 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +package memo_test + +import ( + "testing" + + "gopl.io/ch9/memo5" + "gopl.io/ch9/memotest" +) + +var httpGetBody = memotest.HTTPGetBody + +func Test(t *testing.T) { + m := memo.New(httpGetBody) + defer m.Close() + memotest.Sequential(t, m) +} + +func TestConcurrent(t *testing.T) { + m := memo.New(httpGetBody) + defer m.Close() + memotest.Concurrent(t, m) +} diff --git a/vendor/gopl.io/ch9/memotest/memotest.go b/vendor/gopl.io/ch9/memotest/memotest.go new file mode 100644 index 0000000..aab1acf --- /dev/null +++ b/vendor/gopl.io/ch9/memotest/memotest.go @@ -0,0 +1,102 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// See page 272. + +// Package memotest provides common functions for +// testing various designs of the memo package. +package memotest + +import ( + "fmt" + "io/ioutil" + "log" + "net/http" + "sync" + "testing" + "time" +) + +//!+httpRequestBody +func httpGetBody(url string) (interface{}, error) { + resp, err := http.Get(url) + if err != nil { + return nil, err + } + defer resp.Body.Close() + return ioutil.ReadAll(resp.Body) +} + +//!-httpRequestBody + +var HTTPGetBody = httpGetBody + +func incomingURLs() <-chan string { + ch := make(chan string) + go func() { + for _, url := range []string{ + "https://golang.org", + "https://godoc.org", + "https://play.golang.org", + "http://gopl.io", + "https://golang.org", + "https://godoc.org", + "https://play.golang.org", + "http://gopl.io", + } { + ch <- url + } + close(ch) + }() + return ch +} + +type M interface { + Get(key string) (interface{}, error) +} + +/* +//!+seq + m := memo.New(httpGetBody) +//!-seq +*/ + +func Sequential(t *testing.T, m M) { + //!+seq + for url := range incomingURLs() { + start := time.Now() + value, err := m.Get(url) + if err != nil { + log.Print(err) + } + fmt.Printf("%s, %s, %d bytes\n", + url, time.Since(start), len(value.([]byte))) + } + //!-seq +} + +/* +//!+conc + m := memo.New(httpGetBody) +//!-conc +*/ + +func Concurrent(t *testing.T, m M) { + //!+conc + var n sync.WaitGroup + for url := range incomingURLs() { + n.Add(1) + go func(url string) { + start := time.Now() + value, err := m.Get(url) + if err != nil { + log.Print(err) + } + fmt.Printf("%s, %s, %d bytes\n", + url, time.Since(start), len(value.([]byte))) + n.Done() + }(url) + } + n.Wait() + //!-conc +} diff --git a/zh2tw.go b/zh2tw.go new file mode 100644 index 0000000..139652f --- /dev/null +++ b/zh2tw.go @@ -0,0 +1,4351 @@ +// Copyright 2013 . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build ingore + +// +// 简体字转繁体字, 1:1转换, 支持逆向转换. +// +// Example: +// zh2tw dir +// zh2tw dir "\.go$" +// zh2tw dir "\.md$" zh2tw +// zh2tw dir "\.md$" tw2zh +// +// Help: +// zh2tw -h +// +package main + +import ( + "fmt" + "io/ioutil" + "log" + "os" + "path/filepath" + "regexp" +) + +const usage = ` +Usage: zh2tw dir [nameFilter] + zh2tw -h + +Example: + zh2tw dir + zh2tw dir "\.go$" + zh2tw dir "\.md$" zh2tw + zh2tw dir "\.md$" tw2zh + +Report bugs to . +` + +func main() { + if len(os.Args) < 2 || os.Args[1] == "-h" { + fmt.Fprintln(os.Stderr, usage[1:len(usage)-1]) + os.Exit(0) + } + dir, nameFilter, method := os.Args[1], ".*", "zh2tw" + if len(os.Args) > 2 { + nameFilter = os.Args[2] + } + if len(os.Args) > 3 { + method = os.Args[3] + } + + if method != "zh2tw" && method != "tw2zh" { + fmt.Fprintln(os.Stderr, usage[1:len(usage)-1]) + os.Exit(0) + } + + total := 0 + filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + if err != nil { + log.Fatal("filepath.Walk: ", err) + return err + } + if info.IsDir() { + return nil + } + relpath, err := filepath.Rel(dir, path) + if err != nil { + log.Fatal("filepath.Rel: ", err) + return err + } + mathed, err := regexp.MatchString(nameFilter, relpath) + if err != nil { + log.Fatal("regexp.MatchString: ", err) + } + if mathed { + if changed := convertFile(path, method); changed { + fmt.Printf("%s\n", relpath) + } + total++ + } + return nil + }) + fmt.Printf("%s total %d\n", method, total) +} + +func convertFile(path, method string) (changed bool) { + abspath, err := filepath.Abs(path) + if err != nil { + log.Fatal("convertFile: filepath.Abs:", err) + } + + oldData, err := ioutil.ReadFile(abspath) + if err != nil { + log.Fatal("convertFile: ioutil.ReadFile:", err) + } + + newData := oldData + switch { + case method == "zh2tw": + newData = []byte(zh2tw(string(oldData))) + case method == "tw2zh": + newData = []byte(tw2zh(string(oldData))) + } + + if string(newData) == string(oldData) { + return false + } + + err = ioutil.WriteFile(abspath, newData, 0666) + if err != nil { + log.Fatal("convertFile: ioutil.WriteFile:", err) + } + return true +} + +func zh2tw(s string) string { + old := []rune(s) + new := make([]rune, 0) + for _, c := range old { + if x, ok := zh2twMap[c]; ok { + new = append(new, x) + } else { + new = append(new, c) + } + } + return string(new) +} + +func tw2zh(s string) string { + old := []rune(s) + new := make([]rune, 0) + for _, c := range old { + if x, ok := tw2zhMap[c]; ok { + new = append(new, x) + } else { + new = append(new, c) + } + } + return string(new) +} + +func init() { + // 剔除出现多次的字符 + vvMap := make(map[rune]int) + for k, v := range _TSCharactersMap { + vvMap[k]++ + vvMap[v]++ + } + for k, v := range _TSCharactersMap { + if vvMap[k] > 1 { + delete(_TSCharactersMap, k) + } + if vvMap[v] > 1 { + delete(_TSCharactersMap, v) + } + } + for k, v := range _TSCharactersMap { + zh2twMap[v] = k + } +} + +var ( + zh2twMap = make(map[rune]rune) + tw2zhMap = _TSCharactersMap +) + +var _TSCharactersMap = map[rune]rune{ + '㑮': '𫝈', + '㑯': '㑔', + '㑳': '㑇', + '㑶': '㐹', + '㒓': '𠉂', + '㓄': '𪠟', + '㓨': '刾', + '㔋': '𪟎', + '㖮': '𪠵', + '㗲': '𠵾', + '㗿': '𪡛', + '㘉': '𠰱', + '㘓': '𪢌', + '㘔': '㗷', + '㘚': '㘎', + '㛝': '𫝦', + '㜄': '㚯', + '㜏': '㛣', + '㜐': '𫝧', + '㜗': '𡞋', + '㜢': '𡞱', + '㜷': '𡝠', + '㞞': '𪨊', + '㟺': '𪩇', + '㠏': '㟆', + '㢗': '𪪑', + '㢝': '𢋈', + '㥮': '㤘', + '㦎': '𢛯', + '㦛': '𢗓', + '㦞': '𪫷', + '㨻': '𪮃', + '㩋': '𪮋', + '㩜': '㨫', + '㩳': '㧐', + '㩵': '擜', + '㪎': '𪯋', + '㯤': '𣘐', + '㰙': '𣗙', + '㵗': '𣳆', + '㵾': '𪷍', + '㶆': '𫞛', + '㷍': '𤆢', + '㷿': '𤈷', + '㸇': '𤎺', + '㹽': '𫞣', + '㺏': '𤠋', + '㺜': '𪺻', + '㻶': '𪼋', + '㿖': '𪽮', + '㿗': '𤻊', + '㿧': '𤽯', + '䀉': '𥁢', + '䀹': '𥅴', + '䁪': '𥇢', + '䁻': '䀥', + '䂎': '𥎝', + '䅐': '𫀨', + '䅳': '𫀬', + '䆉': '𫁂', + '䉑': '𫁲', + '䉙': '𥬀', + '䉬': '𫂈', + '䉲': '𥮜', + '䉶': '𫁷', + '䊭': '𥺅', + '䊷': '䌶', + '䊺': '𫄚', + '䋃': '𫄜', + '䋔': '𫄞', + '䋙': '䌺', + '䋚': '䌻', + '䋦': '𫄩', + '䋹': '䌿', + '䋻': '䌾', + '䋼': '𫄮', + '䋿': '𦈓', + '䌈': '𦈖', + '䌋': '𦈘', + '䌖': '𦈜', + '䌝': '𦈟', + '䌟': '𦈞', + '䌥': '𦈠', + '䌰': '𦈙', + '䍤': '𫅅', + '䍦': '䍠', + '䍽': '𦍠', + '䎙': '𫅭', + '䎱': '䎬', + '䕤': '𫟕', + '䕳': '𦰴', + '䖅': '𫟑', + '䗅': '𫊪', + '䗿': '𧉞', + '䙔': '𫋲', + '䙡': '䙌', + '䙱': '𧜭', + '䚩': '𫌯', + '䛄': '𫍠', + '䛳': '𫍫', + '䜀': '䜧', + '䜖': '𫟢', + '䝭': '𫎧', + '䝻': '𧹕', + '䝼': '䞍', + '䞈': '𧹑', + '䞋': '𫎪', + '䞓': '𫎭', + '䟃': '𫎺', + '䟆': '𫎳', + '䟐': '𫎱', + '䠆': '𫏃', + '䠱': '𨅛', + '䡐': '𫟤', + '䡩': '𫟥', + '䡵': '𫟦', + '䢨': '𨑹', + '䤤': '𫟺', + '䥄': '𫠀', + '䥇': '䦂', + '䥗': '𫔋', + '䥩': '𨱖', + '䥯': '𫔆', + '䥱': '䥾', + '䦘': '𨸄', + '䦛': '䦶', + '䦟': '䦷', + '䦯': '𫔵', + '䦳': '𨷿', + '䧢': '𨸟', + '䪊': '𫖅', + '䪏': '𩏼', + '䪗': '𩐀', + '䪘': '𩏿', + '䪴': '𫖫', + '䪾': '𫖬', + '䫀': '𫖱', + '䫂': '𫖰', + '䫟': '𫖲', + '䫴': '𩖗', + '䫶': '𫖺', + '䫻': '𫗇', + '䫾': '𫠈', + '䬓': '𫗊', + '䬘': '𩙮', + '䬝': '𩙯', + '䬞': '𩙧', + '䬧': '𫗟', + '䭀': '𩠇', + '䭃': '𩠈', + '䭑': '𫗱', + '䭔': '𫗰', + '䭿': '𩧭', + '䮄': '𫠊', + '䮝': '𩧰', + '䮞': '𩨁', + '䮠': '𩧿', + '䮫': '𩨇', + '䮰': '𫘮', + '䮳': '𩨏', + '䮾': '𩧪', + '䯀': '䯅', + '䯤': '𩩈', + '䰾': '鲃', + '䱀': '𫚐', + '䱁': '𫚏', + '䱙': '𩾈', + '䱧': '𫚠', + '䱬': '𩾊', + '䱰': '𩾋', + '䱷': '䲣', + '䱸': '𫠑', + '䱽': '䲝', + '䲁': '鳚', + '䲅': '𫚜', + '䲖': '𩾂', + '䲘': '鳤', + '䲰': '𪉂', + '䳜': '𫛬', + '䳢': '𫛰', + '䳤': '𫛮', + '䳧': '𫛺', + '䳫': '𫛼', + '䴉': '鹮', + '䴋': '𫜅', + '䴬': '𪎈', + '䴱': '𫜒', + '䴴': '𪎋', + '䴽': '𫜔', + '䵳': '𪑅', + '䵴': '𫜙', + '䶕': '𫜨', + '䶲': '𫜳', + '万': '万', + '丑': '丑', + '丟': '丢', + '並': '并', + '丰': '丰', + '么': '么', + '乾': '干', + '亂': '乱', + '了': '了', + '于': '于', + '云': '云', + '亙': '亘', + '亞': '亚', + '仆': '仆', + '仇': '仇', + '价': '价', + '仿': '仿', + '伙': '伙', + '佇': '伫', + '佈': '布', + '佔': '占', + '余': '余', + '佛': '佛', + '佣': '佣', + '併': '并', + '來': '来', + '侖': '仑', + '侶': '侣', + '侷': '局', + '俁': '俣', + '係': '系', + '俊': '俊', + '俓': '𠇹', + '俔': '伣', + '俠': '侠', + '俥': '伡', + '俬': '私', + '修': '修', + '倀': '伥', + '倆': '俩', + '倈': '俫', + '倉': '仓', + '個': '个', + '們': '们', + '倖': '幸', + '借': '借', + '倫': '伦', + '倲': '㑈', + '偉': '伟', + '偑': '㐽', + '側': '侧', + '偵': '侦', + '偽': '伪', + '傌': '㐷', + '傑': '杰', + '傖': '伧', + '傘': '伞', + '備': '备', + '傢': '家', + '傭': '佣', + '傯': '偬', + '傳': '传', + '傴': '伛', + '債': '债', + '傷': '伤', + '傾': '倾', + '僂': '偻', + '僅': '仅', + '僉': '佥', + '僑': '侨', + '僕': '仆', + '僞': '伪', + '僥': '侥', + '僨': '偾', + '僱': '雇', + '僵': '僵', + '價': '价', + '儀': '仪', + '儁': '俊', + '儂': '侬', + '億': '亿', + '儈': '侩', + '儉': '俭', + '儎': '傤', + '儐': '傧', + '儔': '俦', + '儕': '侪', + '儘': '尽', + '償': '偿', + '儣': '𠆲', + '優': '优', + '儭': '𠋆', + '儲': '储', + '儷': '俪', + '儸': '㑩', + '儺': '傩', + '儻': '傥', + '儼': '俨', + '兇': '凶', + '克': '克', + '兌': '兑', + '兒': '儿', + '兗': '兖', + '党': '党', + '內': '内', + '兩': '两', + '冊': '册', + '冑': '胄', + '冪': '幂', + '冬': '冬', + '准': '准', + '凈': '净', + '凌': '凌', + '凍': '冻', + '凙': '𪞝', + '凜': '凛', + '几': '几', + '凱': '凯', + '凶': '凶', + '出': '出', + '划': '划', + '別': '别', + '刪': '删', + '刮': '刮', + '制': '制', + '剄': '刭', + '則': '则', + '剋': '克', + '剎': '刹', + '剗': '刬', + '剛': '刚', + '剝': '剥', + '剮': '剐', + '剴': '剀', + '創': '创', + '剷': '铲', + '剾': '𠛅', + '劃': '划', + '劇': '剧', + '劉': '刘', + '劊': '刽', + '劌': '刿', + '劍': '剑', + '劏': '㓥', + '劑': '剂', + '劚': '㔉', + '勁': '劲', + '勑': '𠡠', + '動': '动', + '務': '务', + '勛': '勋', + '勝': '胜', + '勞': '劳', + '勢': '势', + '勣': '𪟝', + '勩': '勚', + '勱': '劢', + '勳': '勋', + '勵': '励', + '勸': '劝', + '勻': '匀', + '匭': '匦', + '匯': '汇', + '匱': '匮', + '區': '区', + '千': '千', + '升': '升', + '協': '协', + '卜': '卜', + '占': '占', + '卷': '卷', + '卹': '恤', + '卻': '却', + '卽': '即', + '厂': '厂', + '厘': '厘', + '厙': '厍', + '厠': '厕', + '厤': '历', + '厭': '厌', + '厲': '厉', + '厴': '厣', + '參': '参', + '叄': '叁', + '叢': '丛', + '只': '只', + '台': '台', + '叶': '叶', + '吁': '吁', + '合': '合', + '吊': '吊', + '同': '同', + '后': '后', + '向': '向', + '吒': '咤', + '吳': '吴', + '吶': '呐', + '呂': '吕', + '周': '周', + '咨': '咨', + '咸': '咸', + '咼': '呙', + '咽': '咽', + '哄': '哄', + '員': '员', + '哯': '𠯟', + '唄': '呗', + '唓': '𪠳', + '唚': '吣', + '唸': '念', + '問': '问', + '啓': '启', + '啞': '哑', + '啟': '启', + '啢': '唡', + '喂': '喂', + '喎': '㖞', + '喚': '唤', + '喪': '丧', + '喫': '吃', + '喬': '乔', + '單': '单', + '喲': '哟', + '嗆': '呛', + '嗇': '啬', + '嗊': '唝', + '嗎': '吗', + '嗚': '呜', + '嗩': '唢', + '嗰': '𠮶', + '嗶': '哔', + '嗹': '𪡏', + '嘆': '叹', + '嘍': '喽', + '嘓': '啯', + '嘔': '呕', + '嘖': '啧', + '嘗': '尝', + '嘜': '唛', + '嘩': '哗', + '嘪': '𪡃', + '嘮': '唠', + '嘯': '啸', + '嘰': '叽', + '嘳': '𪡞', + '嘵': '哓', + '嘸': '呒', + '嘺': '𪡀', + '嘽': '啴', + '噁': '恶', + '噅': '𠯠', + '噓': '嘘', + '噚': '㖊', + '噝': '咝', + '噞': '𪡋', + '噠': '哒', + '噥': '哝', + '噦': '哕', + '噪': '噪', + '噯': '嗳', + '噲': '哙', + '噴': '喷', + '噸': '吨', + '噹': '当', + '嚀': '咛', + '嚇': '吓', + '嚌': '哜', + '嚐': '尝', + '嚕': '噜', + '嚙': '啮', + '嚛': '𪠸', + '嚥': '咽', + '嚦': '呖', + '嚧': '𠰷', + '嚨': '咙', + '嚮': '向', + '嚲': '亸', + '嚳': '喾', + '嚴': '严', + '嚶': '嘤', + '嚽': '𪢕', + '囀': '啭', + '囁': '嗫', + '囂': '嚣', + '囃': '𠱞', + '囅': '冁', + '囈': '呓', + '囉': '啰', + '囌': '苏', + '囑': '嘱', + '囒': '𪢠', + '回': '回', + '囪': '囱', + '困': '困', + '圇': '囵', + '國': '国', + '圍': '围', + '園': '园', + '圓': '圆', + '圖': '图', + '團': '团', + '圞': '𪢮', + '坐': '坐', + '垵': '埯', + '埡': '垭', + '埬': '𪣆', + '埰': '采', + '執': '执', + '堅': '坚', + '堊': '垩', + '堖': '垴', + '堚': '𪣒', + '堝': '埚', + '堯': '尧', + '報': '报', + '場': '场', + '塊': '块', + '塋': '茔', + '塏': '垲', + '塒': '埘', + '塗': '涂', + '塚': '冢', + '塢': '坞', + '塤': '埙', + '塵': '尘', + '塹': '堑', + '塿': '𪣻', + '墊': '垫', + '墜': '坠', + '墮': '堕', + '墰': '坛', + '墲': '𪢸', + '墳': '坟', + '墶': '垯', + '墻': '墙', + '墾': '垦', + '壇': '坛', + '壈': '𡒄', + '壋': '垱', + '壎': '埙', + '壓': '压', + '壗': '𡋤', + '壘': '垒', + '壙': '圹', + '壚': '垆', + '壜': '坛', + '壞': '坏', + '壟': '垄', + '壠': '垅', + '壢': '坜', + '壣': '𪤚', + '壩': '坝', + '壪': '塆', + '壯': '壮', + '壺': '壶', + '壼': '壸', + '壽': '寿', + '夠': '够', + '夢': '梦', + '夥': '伙', + '夸': '夸', + '夾': '夹', + '奐': '奂', + '奧': '奥', + '奩': '奁', + '奪': '夺', + '奬': '奖', + '奮': '奋', + '奸': '奸', + '奼': '姹', + '妝': '妆', + '姍': '姗', + '姜': '姜', + '姦': '奸', + '娘': '娘', + '娛': '娱', + '婁': '娄', + '婡': '𫝫', + '婦': '妇', + '婭': '娅', + '媈': '𫝨', + '媧': '娲', + '媯': '妫', + '媰': '㛀', + '媼': '媪', + '媽': '妈', + '嫋': '袅', + '嫗': '妪', + '嫵': '妩', + '嫺': '娴', + '嫻': '娴', + '嫿': '婳', + '嬀': '妫', + '嬃': '媭', + '嬇': '𫝬', + '嬈': '娆', + '嬋': '婵', + '嬌': '娇', + '嬙': '嫱', + '嬡': '嫒', + '嬣': '𪥰', + '嬤': '嬷', + '嬦': '𫝩', + '嬪': '嫔', + '嬰': '婴', + '嬸': '婶', + '嬻': '𪥿', + '孃': '娘', + '孄': '𫝮', + '孆': '𫝭', + '孇': '𪥫', + '孋': '㛤', + '孌': '娈', + '孎': '𡠟', + '孫': '孙', + '學': '学', + '孻': '𡥧', + '孾': '𪧀', + '孿': '孪', + '宮': '宫', + '家': '家', + '寀': '采', + '寠': '𪧘', + '寢': '寝', + '實': '实', + '寧': '宁', + '審': '审', + '寫': '写', + '寬': '宽', + '寵': '宠', + '寶': '宝', + '將': '将', + '專': '专', + '尋': '寻', + '對': '对', + '導': '导', + '尷': '尴', + '尸': '尸', + '局': '局', + '屆': '届', + '屍': '尸', + '屓': '屃', + '屜': '屉', + '屢': '屡', + '層': '层', + '屨': '屦', + '屩': '𪨗', + '屬': '属', + '岡': '冈', + '岩': '岩', + '峯': '峰', + '峴': '岘', + '島': '岛', + '峽': '峡', + '崍': '崃', + '崑': '昆', + '崗': '岗', + '崙': '仑', + '崢': '峥', + '崬': '岽', + '嵐': '岚', + '嵗': '岁', + '嵼': '𡶴', + '嵾': '㟥', + '嶁': '嵝', + '嶄': '崭', + '嶇': '岖', + '嶈': '𡺃', + '嶔': '嵚', + '嶗': '崂', + '嶘': '𡺄', + '嶠': '峤', + '嶢': '峣', + '嶧': '峄', + '嶨': '峃', + '嶮': '崄', + '嶴': '岙', + '嶸': '嵘', + '嶹': '𫝵', + '嶺': '岭', + '嶼': '屿', + '嶽': '岳', + '巊': '𪩎', + '巋': '岿', + '巒': '峦', + '巔': '巅', + '巖': '岩', + '巗': '𪨷', + '巘': '𪩘', + '巨': '巨', + '巰': '巯', + '巹': '卺', + '布': '布', + '帘': '帘', + '帥': '帅', + '師': '师', + '席': '席', + '帳': '帐', + '帶': '带', + '幀': '帧', + '幃': '帏', + '幓': '㡎', + '幗': '帼', + '幘': '帻', + '幝': '𪩷', + '幟': '帜', + '幣': '币', + '幩': '𪩸', + '幫': '帮', + '幬': '帱', + '干': '干', + '幸': '幸', + '幹': '干', + '幺': '幺', + '幾': '几', + '广': '广', + '座': '座', + '庫': '库', + '庵': '庵', + '廁': '厕', + '廂': '厢', + '廄': '厩', + '廈': '厦', + '廎': '庼', + '廕': '荫', + '廚': '厨', + '廝': '厮', + '廟': '庙', + '廠': '厂', + '廡': '庑', + '廢': '废', + '廣': '广', + '廧': '𪪞', + '廩': '廪', + '廬': '庐', + '廳': '厅', + '弒': '弑', + '弔': '吊', + '弦': '弦', + '弳': '弪', + '張': '张', + '強': '强', + '彃': '𪪼', + '彆': '别', + '彈': '弹', + '彌': '弥', + '彎': '弯', + '彔': '录', + '彙': '汇', + '彞': '彝', + '彠': '彟', + '彥': '彦', + '彩': '彩', + '彫': '雕', + '彲': '彨', + '彷': '彷', + '彿': '佛', + '征': '征', + '後': '后', + '徑': '径', + '從': '从', + '徠': '徕', + '御': '御', + '復': '复', + '徵': '征', + '徹': '彻', + '徿': '𪫌', + '志': '志', + '念': '念', + '恆': '恒', + '恥': '耻', + '悅': '悦', + '悞': '悮', + '悵': '怅', + '悶': '闷', + '悽': '凄', + '惡': '恶', + '惱': '恼', + '惲': '恽', + '惻': '恻', + '愈': '愈', + '愛': '爱', + '愜': '惬', + '愨': '悫', + '愴': '怆', + '愷': '恺', + '愻': '𢙏', + '愾': '忾', + '愿': '愿', + '慄': '栗', + '態': '态', + '慍': '愠', + '慘': '惨', + '慚': '惭', + '慟': '恸', + '慣': '惯', + '慤': '悫', + '慪': '怄', + '慫': '怂', + '慮': '虑', + '慳': '悭', + '慶': '庆', + '慺': '㥪', + '慼': '戚', + '慾': '欲', + '憂': '忧', + '憊': '惫', + '憐': '怜', + '憑': '凭', + '憒': '愦', + '憖': '慭', + '憚': '惮', + '憢': '𢙒', + '憤': '愤', + '憫': '悯', + '憮': '怃', + '憲': '宪', + '憶': '忆', + '憸': '𪫺', + '憹': '𢙐', + '懀': '𢙓', + '懇': '恳', + '應': '应', + '懌': '怿', + '懍': '懔', + '懎': '𢠁', + '懞': '蒙', + '懟': '怼', + '懣': '懑', + '懤': '㤽', + '懨': '恹', + '懲': '惩', + '懶': '懒', + '懷': '怀', + '懸': '悬', + '懺': '忏', + '懼': '惧', + '懾': '慑', + '戀': '恋', + '戇': '戆', + '戔': '戋', + '戚': '戚', + '戧': '戗', + '戩': '戬', + '戰': '战', + '戱': '戯', + '戲': '戏', + '戶': '户', + '才': '才', + '扎': '扎', + '托': '托', + '扣': '扣', + '折': '折', + '拋': '抛', + '拐': '拐', + '拚': '拚', + '挂': '挂', + '挨': '挨', + '挩': '捝', + '挱': '挲', + '挽': '挽', + '挾': '挟', + '捨': '舍', + '捫': '扪', + '据': '据', + '捱': '挨', + '捲': '卷', + '掃': '扫', + '掄': '抡', + '掆': '㧏', + '掗': '挜', + '掙': '挣', + '掚': '𪭵', + '掛': '挂', + '採': '采', + '揀': '拣', + '揚': '扬', + '換': '换', + '揮': '挥', + '揯': '搄', + '損': '损', + '搖': '摇', + '搗': '捣', + '搜': '搜', + '搵': '揾', + '搶': '抢', + '摋': '𢫬', + '摐': '𪭢', + '摑': '掴', + '摜': '掼', + '摟': '搂', + '摯': '挚', + '摳': '抠', + '摶': '抟', + '摺': '折', + '摻': '掺', + '撈': '捞', + '撊': '𪭾', + '撏': '挦', + '撐': '撑', + '撓': '挠', + '撝': '㧑', + '撟': '挢', + '撣': '掸', + '撥': '拨', + '撧': '𪮖', + '撫': '抚', + '撲': '扑', + '撳': '揿', + '撻': '挞', + '撾': '挝', + '撿': '捡', + '擁': '拥', + '擄': '掳', + '擇': '择', + '擊': '击', + '擋': '挡', + '擓': '㧟', + '擔': '担', + '據': '据', + '擟': '𪭧', + '擠': '挤', + '擡': '抬', + '擣': '捣', + '擫': '𢬍', + '擬': '拟', + '擯': '摈', + '擰': '拧', + '擱': '搁', + '擲': '掷', + '擴': '扩', + '擷': '撷', + '擺': '摆', + '擻': '擞', + '擼': '撸', + '擽': '㧰', + '擾': '扰', + '攄': '摅', + '攆': '撵', + '攋': '𪮶', + '攏': '拢', + '攔': '拦', + '攖': '撄', + '攙': '搀', + '攛': '撺', + '攜': '携', + '攝': '摄', + '攢': '攒', + '攣': '挛', + '攤': '摊', + '攪': '搅', + '攬': '揽', + '敎': '教', + '敓': '敚', + '敗': '败', + '敘': '叙', + '敵': '敌', + '數': '数', + '斂': '敛', + '斃': '毙', + '斅': '𢽾', + '斆': '敩', + '斕': '斓', + '斗': '斗', + '斬': '斩', + '斷': '断', + '斸': '𣃁', + '於': '于', + '旂': '旗', + '旣': '既', + '昆': '昆', + '昇': '升', + '時': '时', + '晉': '晋', + '晝': '昼', + '暈': '晕', + '暉': '晖', + '暗': '暗', + '暘': '旸', + '暢': '畅', + '暫': '暂', + '曄': '晔', + '曆': '历', + '曇': '昙', + '曉': '晓', + '曊': '𪰶', + '曏': '向', + '曖': '暧', + '曠': '旷', + '曥': '𣆐', + '曨': '昽', + '曬': '晒', + '曲': '曲', + '書': '书', + '會': '会', + '朥': '𦛨', + '朧': '胧', + '朮': '术', + '朱': '朱', + '朴': '朴', + '杆': '杆', + '杠': '杠', + '杯': '杯', + '杰': '杰', + '東': '东', + '杴': '锨', + '松': '松', + '板': '板', + '极': '极', + '枴': '拐', + '柜': '柜', + '柵': '栅', + '柺': '拐', + '査': '查', + '栗': '栗', + '核': '核', + '桱': '𣐕', + '桿': '杆', + '梁': '梁', + '梔': '栀', + '梖': '𪱷', + '梘': '枧', + '條': '条', + '梟': '枭', + '梲': '棁', + '棄': '弃', + '棊': '棋', + '棖': '枨', + '棗': '枣', + '棟': '栋', + '棡': '㭎', + '棧': '栈', + '棱': '棱', + '棲': '栖', + '棶': '梾', + '椏': '桠', + '椲': '㭏', + '楇': '𣒌', + '楊': '杨', + '楓': '枫', + '楨': '桢', + '業': '业', + '極': '极', + '榘': '矩', + '榦': '干', + '榪': '杩', + '榮': '荣', + '榲': '榅', + '榿': '桤', + '構': '构', + '槍': '枪', + '槓': '杠', + '槤': '梿', + '槧': '椠', + '槨': '椁', + '槫': '𣏢', + '槮': '椮', + '槳': '桨', + '槶': '椢', + '槼': '椝', + '樁': '桩', + '樂': '乐', + '樅': '枞', + '樑': '梁', + '樓': '楼', + '標': '标', + '樞': '枢', + '樠': '𣗊', + '樢': '㭤', + '樣': '样', + '樤': '𣔌', + '樧': '榝', + '樫': '㭴', + '樳': '桪', + '樸': '朴', + '樹': '树', + '樺': '桦', + '樿': '椫', + '橈': '桡', + '橋': '桥', + '機': '机', + '橢': '椭', + '橫': '横', + '橯': '𣓿', + '檁': '檩', + '檉': '柽', + '檔': '档', + '檜': '桧', + '檟': '槚', + '檢': '检', + '檣': '樯', + '檭': '𣘴', + '檮': '梼', + '檯': '台', + '檳': '槟', + '檵': '𪲛', + '檸': '柠', + '檻': '槛', + '檾': '𦼖', + '櫃': '柜', + '櫅': '𪲎', + '櫓': '橹', + '櫚': '榈', + '櫛': '栉', + '櫝': '椟', + '櫞': '橼', + '櫟': '栎', + '櫠': '𪲮', + '櫥': '橱', + '櫧': '槠', + '櫨': '栌', + '櫪': '枥', + '櫫': '橥', + '櫬': '榇', + '櫱': '蘖', + '櫳': '栊', + '櫸': '榉', + '櫺': '棂', + '櫻': '樱', + '欄': '栏', + '欅': '榉', + '欇': '𪳍', + '權': '权', + '欍': '𣐤', + '欏': '椤', + '欐': '𪲔', + '欑': '𪴙', + '欒': '栾', + '欓': '𣗋', + '欖': '榄', + '欘': '𣚚', + '欞': '棂', + '欲': '欲', + '欽': '钦', + '歎': '叹', + '歐': '欧', + '歟': '欤', + '歡': '欢', + '歲': '岁', + '歷': '历', + '歸': '归', + '歿': '殁', + '殘': '残', + '殞': '殒', + '殢': '𣨼', + '殤': '殇', + '殨': '㱮', + '殫': '殚', + '殭': '僵', + '殮': '殓', + '殯': '殡', + '殰': '㱩', + '殲': '歼', + '殺': '杀', + '殻': '壳', + '殼': '壳', + '毀': '毁', + '毆': '殴', + '毊': '𪵑', + '毿': '毵', + '氂': '牦', + '氈': '毡', + '氌': '氇', + '氣': '气', + '氫': '氢', + '氬': '氩', + '氭': '𣱝', + '氳': '氲', + '氾': '泛', + '汎': '泛', + '汙': '污', + '決': '决', + '沈': '沈', + '沒': '没', + '沖': '冲', + '況': '况', + '泛': '泛', + '泝': '溯', + '注': '注', + '洩': '泄', + '洶': '汹', + '浹': '浃', + '涂': '涂', + '涇': '泾', + '涌': '涌', + '涗': '涚', + '涼': '凉', + '淀': '淀', + '淒': '凄', + '淚': '泪', + '淥': '渌', + '淨': '净', + '淩': '凌', + '淪': '沦', + '淵': '渊', + '淶': '涞', + '淺': '浅', + '渙': '涣', + '減': '减', + '渢': '沨', + '渦': '涡', + '測': '测', + '游': '游', + '渾': '浑', + '湊': '凑', + '湋': '𣲗', + '湞': '浈', + '湧': '涌', + '湯': '汤', + '溈': '沩', + '準': '准', + '溝': '沟', + '溡': '𪶄', + '溫': '温', + '溮': '浉', + '溳': '涢', + '溼': '湿', + '滄': '沧', + '滅': '灭', + '滌': '涤', + '滎': '荥', + '滙': '汇', + '滬': '沪', + '滯': '滞', + '滲': '渗', + '滷': '卤', + '滸': '浒', + '滻': '浐', + '滾': '滚', + '滿': '满', + '漁': '渔', + '漊': '溇', + '漓': '漓', + '漚': '沤', + '漢': '汉', + '漣': '涟', + '漬': '渍', + '漲': '涨', + '漵': '溆', + '漸': '渐', + '漿': '浆', + '潁': '颍', + '潑': '泼', + '潔': '洁', + '潕': '𣲘', + '潙': '沩', + '潚': '㴋', + '潛': '潜', + '潣': '𫞗', + '潤': '润', + '潯': '浔', + '潰': '溃', + '潷': '滗', + '潿': '涠', + '澀': '涩', + '澅': '𣶩', + '澆': '浇', + '澇': '涝', + '澐': '沄', + '澗': '涧', + '澠': '渑', + '澤': '泽', + '澦': '滪', + '澩': '泶', + '澬': '𫞚', + '澮': '浍', + '澱': '淀', + '澾': '㳠', + '濁': '浊', + '濃': '浓', + '濄': '㳡', + '濆': '𣸣', + '濕': '湿', + '濘': '泞', + '濚': '溁', + '濛': '蒙', + '濜': '浕', + '濟': '济', + '濤': '涛', + '濧': '㳔', + '濫': '滥', + '濰': '潍', + '濱': '滨', + '濺': '溅', + '濼': '泺', + '濾': '滤', + '濿': '𪵱', + '瀂': '澛', + '瀃': '𣽷', + '瀅': '滢', + '瀆': '渎', + '瀇': '㲿', + '瀉': '泻', + '瀋': '沈', + '瀏': '浏', + '瀕': '濒', + '瀘': '泸', + '瀝': '沥', + '瀟': '潇', + '瀠': '潆', + '瀦': '潴', + '瀧': '泷', + '瀨': '濑', + '瀰': '弥', + '瀲': '潋', + '瀾': '澜', + '灃': '沣', + '灄': '滠', + '灍': '𫞝', + '灑': '洒', + '灒': '𪷽', + '灕': '漓', + '灘': '滩', + '灙': '𣺼', + '灝': '灏', + '灡': '㳕', + '灣': '湾', + '灤': '滦', + '灧': '滟', + '灩': '滟', + '災': '灾', + '為': '为', + '烏': '乌', + '烴': '烃', + '無': '无', + '煇': '𪸩', + '煉': '炼', + '煒': '炜', + '煙': '烟', + '煢': '茕', + '煥': '焕', + '煩': '烦', + '煬': '炀', + '煱': '㶽', + '熂': '𪸕', + '熅': '煴', + '熉': '𤈶', + '熌': '𤇄', + '熏': '熏', + '熒': '荧', + '熓': '𤆡', + '熗': '炝', + '熚': '𤇹', + '熡': '𤋏', + '熱': '热', + '熲': '颎', + '熾': '炽', + '燁': '烨', + '燈': '灯', + '燉': '炖', + '燒': '烧', + '燙': '烫', + '燜': '焖', + '營': '营', + '燦': '灿', + '燬': '毁', + '燭': '烛', + '燴': '烩', + '燶': '㶶', + '燻': '熏', + '燼': '烬', + '燾': '焘', + '爃': '𫞡', + '爄': '𤇃', + '爇': '𦶟', + '爍': '烁', + '爐': '炉', + '爖': '𤇭', + '爛': '烂', + '爥': '𪹳', + '爧': '𫞠', + '爭': '争', + '爲': '为', + '爺': '爷', + '爾': '尔', + '牀': '床', + '牆': '墙', + '牘': '牍', + '牴': '牴', + '牽': '牵', + '犖': '荦', + '犛': '牦', + '犞': '𪺭', + '犢': '犊', + '犧': '牺', + '狀': '状', + '狹': '狭', + '狽': '狈', + '猌': '𪺽', + '猙': '狰', + '猶': '犹', + '猻': '狲', + '獁': '犸', + '獃': '呆', + '獄': '狱', + '獅': '狮', + '獊': '𪺷', + '獎': '奖', + '獨': '独', + '獩': '𤞃', + '獪': '狯', + '獫': '猃', + '獮': '狝', + '獰': '狞', + '獱': '㺍', + '獲': '获', + '獵': '猎', + '獷': '犷', + '獸': '兽', + '獺': '獭', + '獻': '献', + '獼': '猕', + '玀': '猡', + '玁': '𤞤', + '珼': '𫞥', + '現': '现', + '琱': '雕', + '琺': '珐', + '琿': '珲', + '瑋': '玮', + '瑒': '玚', + '瑣': '琐', + '瑤': '瑶', + '瑩': '莹', + '瑪': '玛', + '瑲': '玱', + '瑻': '𪻲', + '瑽': '𪻐', + '璉': '琏', + '璊': '𫞩', + '璝': '𪻺', + '璡': '琎', + '璣': '玑', + '璦': '瑷', + '璫': '珰', + '璯': '㻅', + '環': '环', + '璵': '玙', + '璸': '瑸', + '璼': '𫞨', + '璽': '玺', + '璾': '𫞦', + '瓄': '𪻨', + '瓊': '琼', + '瓏': '珑', + '瓔': '璎', + '瓕': '𤦀', + '瓚': '瓒', + '瓛': '𤩽', + '瓮': '瓮', + '甌': '瓯', + '甕': '瓮', + '產': '产', + '産': '产', + '甦': '苏', + '甯': '宁', + '畝': '亩', + '畢': '毕', + '畫': '画', + '異': '异', + '畵': '画', + '當': '当', + '畼': '𪽈', + '疇': '畴', + '疊': '叠', + '症': '症', + '痙': '痉', + '痠': '酸', + '痮': '𪽪', + '痾': '疴', + '瘂': '痖', + '瘋': '疯', + '瘍': '疡', + '瘓': '痪', + '瘞': '瘗', + '瘡': '疮', + '瘧': '疟', + '瘮': '瘆', + '瘱': '𪽷', + '瘲': '疭', + '瘺': '瘘', + '瘻': '瘘', + '療': '疗', + '癆': '痨', + '癇': '痫', + '癉': '瘅', + '癐': '𤶊', + '癒': '愈', + '癘': '疠', + '癟': '瘪', + '癡': '痴', + '癢': '痒', + '癤': '疖', + '癥': '症', + '癧': '疬', + '癩': '癞', + '癬': '癣', + '癭': '瘿', + '癮': '瘾', + '癰': '痈', + '癱': '瘫', + '癲': '癫', + '發': '发', + '皁': '皂', + '皚': '皑', + '皟': '𤾀', + '皰': '疱', + '皸': '皲', + '皺': '皱', + '盃': '杯', + '盜': '盗', + '盞': '盏', + '盡': '尽', + '監': '监', + '盤': '盘', + '盧': '卢', + '盨': '𪾔', + '盪': '荡', + '眝': '𪾣', + '眞': '真', + '眥': '眦', + '眾': '众', + '睍': '𪾢', + '睏': '困', + '睜': '睁', + '睞': '睐', + '睪': '睾', + '瞘': '眍', + '瞜': '䁖', + '瞞': '瞒', + '瞤': '𥆧', + '瞭': '瞭', + '瞶': '瞆', + '瞼': '睑', + '矇': '蒙', + '矉': '𪾸', + '矑': '𪾦', + '矓': '眬', + '矚': '瞩', + '矩': '矩', + '矯': '矫', + '硃': '朱', + '硜': '硁', + '硤': '硖', + '硨': '砗', + '确': '确', + '硯': '砚', + '碕': '埼', + '碙': '𥐻', + '碩': '硕', + '碭': '砀', + '碸': '砜', + '確': '确', + '碼': '码', + '碽': '䂵', + '磑': '硙', + '磚': '砖', + '磠': '硵', + '磣': '碜', + '磧': '碛', + '磯': '矶', + '磽': '硗', + '磾': '䃅', + '礄': '硚', + '礆': '硷', + '礎': '础', + '礒': '𥐟', + '礙': '碍', + '礦': '矿', + '礪': '砺', + '礫': '砾', + '礬': '矾', + '礮': '𪿫', + '礱': '砻', + '祇': '祇', + '祕': '秘', + '祘': '祘', + '祿': '禄', + '禍': '祸', + '禎': '祯', + '禕': '祎', + '禡': '祃', + '禦': '御', + '禪': '禅', + '禮': '礼', + '禰': '祢', + '禱': '祷', + '禿': '秃', + '私': '私', + '秈': '籼', + '秋': '秋', + '种': '种', + '稅': '税', + '稈': '秆', + '稏': '䅉', + '稜': '棱', + '稟': '禀', + '種': '种', + '稱': '称', + '穀': '谷', + '穇': '䅟', + '穌': '稣', + '積': '积', + '穎': '颖', + '穗': '穗', + '穠': '秾', + '穡': '穑', + '穢': '秽', + '穩': '稳', + '穫': '获', + '穭': '穞', + '窩': '窝', + '窪': '洼', + '窮': '穷', + '窯': '窑', + '窵': '窎', + '窶': '窭', + '窺': '窥', + '竄': '窜', + '竅': '窍', + '竇': '窦', + '竈': '灶', + '竊': '窃', + '竚': '𥩟', + '竪': '竖', + '竱': '𫁟', + '競': '竞', + '筆': '笔', + '筍': '笋', + '筑': '筑', + '筧': '笕', + '筴': '䇲', + '箇': '个', + '箋': '笺', + '箏': '筝', + '節': '节', + '範': '范', + '築': '筑', + '篋': '箧', + '篔': '筼', + '篘': '𥬠', + '篠': '筿', + '篤': '笃', + '篩': '筛', + '篳': '筚', + '篸': '𥮾', + '簀': '箦', + '簂': '𫂆', + '簍': '篓', + '簑': '蓑', + '簞': '箪', + '簡': '简', + '簢': '𫂃', + '簣': '篑', + '簫': '箫', + '簹': '筜', + '簽': '签', + '簾': '帘', + '籃': '篮', + '籅': '𥫣', + '籋': '𥬞', + '籌': '筹', + '籔': '䉤', + '籙': '箓', + '籛': '篯', + '籜': '箨', + '籟': '籁', + '籠': '笼', + '籤': '签', + '籩': '笾', + '籪': '簖', + '籬': '篱', + '籮': '箩', + '籲': '吁', + '粵': '粤', + '糉': '粽', + '糝': '糁', + '糞': '粪', + '糧': '粮', + '糰': '团', + '糲': '粝', + '糴': '籴', + '糶': '粜', + '糹': '纟', + '糺': '𫄙', + '系': '系', + '糾': '纠', + '紀': '纪', + '紂': '纣', + '約': '约', + '紅': '红', + '紆': '纡', + '紇': '纥', + '紈': '纨', + '紉': '纫', + '紋': '纹', + '納': '纳', + '紐': '纽', + '紓': '纾', + '純': '纯', + '紕': '纰', + '紖': '纼', + '紗': '纱', + '紘': '纮', + '紙': '纸', + '級': '级', + '紛': '纷', + '紜': '纭', + '紝': '纴', + '紟': '𫄛', + '紡': '纺', + '紬': '䌷', + '紮': '扎', + '累': '累', + '細': '细', + '紱': '绂', + '紲': '绁', + '紳': '绅', + '紵': '纻', + '紹': '绍', + '紺': '绀', + '紼': '绋', + '紿': '绐', + '絀': '绌', + '絁': '𫄟', + '終': '终', + '絃': '弦', + '組': '组', + '絅': '䌹', + '絆': '绊', + '絍': '𫟃', + '絎': '绗', + '結': '结', + '絕': '绝', + '絙': '𫄠', + '絛': '绦', + '絝': '绔', + '絞': '绞', + '絡': '络', + '絢': '绚', + '絥': '𫄢', + '給': '给', + '絧': '𫄡', + '絨': '绒', + '絰': '绖', + '統': '统', + '絲': '丝', + '絳': '绛', + '絶': '绝', + '絹': '绢', + '絺': '𫄨', + '綀': '𦈌', + '綁': '绑', + '綃': '绡', + '綆': '绠', + '綇': '𦈋', + '綈': '绨', + '綉': '绣', + '綋': '𫟄', + '綌': '绤', + '綏': '绥', + '綐': '䌼', + '綑': '捆', + '經': '经', + '綖': '𫄧', + '綜': '综', + '綞': '缍', + '綟': '𫄫', + '綠': '绿', + '綡': '𫟅', + '綢': '绸', + '綣': '绻', + '綫': '线', + '綬': '绶', + '維': '维', + '綯': '绹', + '綰': '绾', + '綱': '纲', + '網': '网', + '綳': '绷', + '綴': '缀', + '綵': '彩', + '綸': '纶', + '綹': '绺', + '綺': '绮', + '綻': '绽', + '綽': '绰', + '綾': '绫', + '綿': '绵', + '緄': '绲', + '緇': '缁', + '緊': '紧', + '緋': '绯', + '緍': '𦈏', + '緑': '绿', + '緒': '绪', + '緓': '绬', + '緔': '绱', + '緗': '缃', + '緘': '缄', + '緙': '缂', + '線': '线', + '緝': '缉', + '緞': '缎', + '緟': '𫟆', + '締': '缔', + '緡': '缗', + '緣': '缘', + '緤': '𫄬', + '緦': '缌', + '編': '编', + '緩': '缓', + '緬': '缅', + '緮': '𫄭', + '緯': '纬', + '緰': '𦈕', + '緱': '缑', + '緲': '缈', + '練': '练', + '緶': '缏', + '緷': '𦈉', + '緸': '𦈑', + '緹': '缇', + '緻': '致', + '緼': '缊', + '縈': '萦', + '縉': '缙', + '縊': '缢', + '縋': '缒', + '縍': '𫄰', + '縎': '𦈔', + '縐': '绉', + '縑': '缣', + '縕': '缊', + '縗': '缞', + '縛': '缚', + '縝': '缜', + '縞': '缟', + '縟': '缛', + '縣': '县', + '縧': '绦', + '縫': '缝', + '縬': '𦈚', + '縭': '缡', + '縮': '缩', + '縰': '𫄳', + '縱': '纵', + '縲': '缧', + '縳': '䌸', + '縴': '纤', + '縵': '缦', + '縶': '絷', + '縷': '缕', + '縸': '𫄲', + '縹': '缥', + '縺': '𦈐', + '總': '总', + '績': '绩', + '繂': '𫄴', + '繃': '绷', + '繅': '缫', + '繆': '缪', + '繈': '𫄶', + '繏': '𦈝', + '繐': '穗', + '繒': '缯', + '繓': '𦈛', + '織': '织', + '繕': '缮', + '繚': '缭', + '繞': '绕', + '繟': '𦈎', + '繡': '绣', + '繢': '缋', + '繨': '𫄤', + '繩': '绳', + '繪': '绘', + '繫': '系', + '繬': '𫄱', + '繭': '茧', + '繮': '缰', + '繯': '缳', + '繰': '缲', + '繳': '缴', + '繶': '𫄷', + '繷': '𫄣', + '繸': '䍁', + '繹': '绎', + '繻': '𦈡', + '繼': '继', + '繽': '缤', + '繾': '缱', + '繿': '䍀', + '纁': '𫄸', + '纇': '颣', + '纈': '缬', + '纊': '纩', + '續': '续', + '纍': '累', + '纏': '缠', + '纓': '缨', + '纔': '才', + '纖': '纤', + '纗': '𫄹', + '纘': '缵', + '纚': '𫄥', + '纜': '缆', + '缽': '钵', + '罃': '䓨', + '罈': '坛', + '罌': '罂', + '罎': '坛', + '罰': '罚', + '罵': '骂', + '罷': '罢', + '羅': '罗', + '羆': '罴', + '羈': '羁', + '羋': '芈', + '羣': '群', + '羥': '羟', + '羨': '羡', + '義': '义', + '羵': '𫅗', + '羶': '膻', + '習': '习', + '翬': '翚', + '翹': '翘', + '翽': '翙', + '耬': '耧', + '耮': '耢', + '聖': '圣', + '聞': '闻', + '聯': '联', + '聰': '聪', + '聲': '声', + '聳': '耸', + '聵': '聩', + '聶': '聂', + '職': '职', + '聹': '聍', + '聻': '𫆏', + '聽': '听', + '聾': '聋', + '肅': '肃', + '肴': '肴', + '胜': '胜', + '胡': '胡', + '脅': '胁', + '脈': '脉', + '脛': '胫', + '脣': '唇', + '脥': '𣍰', + '脩': '修', + '脫': '脱', + '脹': '胀', + '腊': '腊', + '腌': '腌', + '腎': '肾', + '腖': '胨', + '腡': '脶', + '腦': '脑', + '腪': '𣍯', + '腫': '肿', + '腳': '脚', + '腸': '肠', + '膃': '腽', + '膕': '腘', + '膚': '肤', + '膞': '䏝', + '膠': '胶', + '膢': '𦝼', + '膩': '腻', + '膹': '𪱥', + '膽': '胆', + '膾': '脍', + '膿': '脓', + '臉': '脸', + '臍': '脐', + '臏': '膑', + '臗': '𣎑', + '臘': '腊', + '臚': '胪', + '臟': '脏', + '臠': '脔', + '臢': '臜', + '臥': '卧', + '臨': '临', + '致': '致', + '臺': '台', + '與': '与', + '興': '兴', + '舉': '举', + '舊': '旧', + '舍': '舍', + '舘': '馆', + '艙': '舱', + '艣': '𫇛', + '艤': '舣', + '艦': '舰', + '艫': '舻', + '艱': '艰', + '艷': '艳', + '芻': '刍', + '苧': '苎', + '苹': '苹', + '范': '范', + '茲': '兹', + '荊': '荆', + '荐': '荐', + '莊': '庄', + '莖': '茎', + '莢': '荚', + '莧': '苋', + '菕': '芲', + '華': '华', + '菴': '庵', + '菸': '烟', + '萇': '苌', + '萊': '莱', + '萬': '万', + '萴': '荝', + '萵': '莴', + '葉': '叶', + '葒': '荭', + '著': '著', + '葝': '𫈎', + '葤': '荮', + '葦': '苇', + '葯': '药', + '葷': '荤', + '蒍': '𫇭', + '蒐': '搜', + '蒓': '莼', + '蒔': '莳', + '蒕': '蒀', + '蒙': '蒙', + '蒞': '莅', + '蒭': '𫇴', + '蒼': '苍', + '蓀': '荪', + '蓆': '席', + '蓋': '盖', + '蓧': '𦰏', + '蓮': '莲', + '蓯': '苁', + '蓴': '莼', + '蓽': '荜', + '蔑': '蔑', + '蔔': '卜', + '蔘': '参', + '蔞': '蒌', + '蔣': '蒋', + '蔥': '葱', + '蔦': '茑', + '蔭': '荫', + '蔯': '𫈟', + '蔿': '𫇭', + '蕁': '荨', + '蕆': '蒇', + '蕎': '荞', + '蕒': '荬', + '蕓': '芸', + '蕕': '莸', + '蕘': '荛', + '蕝': '𫈵', + '蕢': '蒉', + '蕩': '荡', + '蕪': '芜', + '蕭': '萧', + '蕳': '𫈉', + '蕷': '蓣', + '蕽': '𫇽', + '薀': '蕰', + '薆': '𫉁', + '薈': '荟', + '薊': '蓟', + '薌': '芗', + '薑': '姜', + '薔': '蔷', + '薘': '荙', + '薟': '莶', + '薦': '荐', + '薩': '萨', + '薰': '薰', + '薳': '䓕', + '薴': '苧', + '薵': '䓓', + '薹': '苔', + '薺': '荠', + '藉': '藉', + '藍': '蓝', + '藎': '荩', + '藝': '艺', + '藥': '药', + '藪': '薮', + '藭': '䓖', + '藴': '蕴', + '藶': '苈', + '藷': '𫉄', + '藹': '蔼', + '藺': '蔺', + '蘀': '萚', + '蘄': '蕲', + '蘆': '芦', + '蘇': '苏', + '蘊': '蕴', + '蘋': '苹', + '蘚': '藓', + '蘞': '蔹', + '蘟': '𦻕', + '蘢': '茏', + '蘭': '兰', + '蘺': '蓠', + '蘿': '萝', + '虆': '蔂', + '處': '处', + '虛': '虚', + '虜': '虏', + '號': '号', + '虧': '亏', + '虫': '虫', + '虯': '虬', + '蛺': '蛱', + '蛻': '蜕', + '蜆': '蚬', + '蜡': '蜡', + '蝕': '蚀', + '蝟': '猬', + '蝦': '虾', + '蝨': '虱', + '蝸': '蜗', + '螄': '蛳', + '螞': '蚂', + '螢': '萤', + '螮': '䗖', + '螻': '蝼', + '螿': '螀', + '蟂': '𫋇', + '蟄': '蛰', + '蟈': '蝈', + '蟎': '螨', + '蟘': '𫋌', + '蟜': '𫊸', + '蟣': '虮', + '蟬': '蝉', + '蟯': '蛲', + '蟲': '虫', + '蟳': '𫊻', + '蟶': '蛏', + '蟻': '蚁', + '蠀': '𧏗', + '蠁': '蚃', + '蠅': '蝇', + '蠆': '虿', + '蠍': '蝎', + '蠐': '蛴', + '蠑': '蝾', + '蠔': '蚝', + '蠙': '𧏖', + '蠟': '蜡', + '蠣': '蛎', + '蠦': '𫊮', + '蠨': '蟏', + '蠱': '蛊', + '蠶': '蚕', + '蠻': '蛮', + '蠾': '𧑏', + '衆': '众', + '衊': '蔑', + '術': '术', + '衕': '同', + '衚': '胡', + '衛': '卫', + '衝': '冲', + '表': '表', + '衹': '衹', + '袞': '衮', + '裊': '袅', + '裏': '里', + '補': '补', + '裝': '装', + '裡': '里', + '製': '制', + '複': '复', + '褌': '裈', + '褘': '袆', + '褲': '裤', + '褳': '裢', + '褸': '褛', + '褻': '亵', + '襀': '𫌀', + '襆': '幞', + '襇': '裥', + '襉': '裥', + '襏': '袯', + '襓': '𫋹', + '襖': '袄', + '襗': '𫋷', + '襘': '𫋻', + '襝': '裣', + '襠': '裆', + '襤': '褴', + '襪': '袜', + '襬': '摆', + '襯': '衬', + '襰': '𧝝', + '襲': '袭', + '襴': '襕', + '襵': '𫌇', + '覆': '覆', + '覈': '核', + '見': '见', + '覎': '觃', + '規': '规', + '覓': '觅', + '視': '视', + '覘': '觇', + '覛': '𫌪', + '覡': '觋', + '覥': '觍', + '覦': '觎', + '親': '亲', + '覬': '觊', + '覯': '觏', + '覲': '觐', + '覷': '觑', + '覹': '𫌭', + '覺': '觉', + '覼': '𫌨', + '覽': '览', + '覿': '觌', + '觀': '观', + '觴': '觞', + '觶': '觯', + '觸': '触', + '訁': '讠', + '訂': '订', + '訃': '讣', + '計': '计', + '訊': '讯', + '訌': '讧', + '討': '讨', + '訐': '讦', + '訑': '𫍙', + '訒': '讱', + '訓': '训', + '訕': '讪', + '訖': '讫', + '託': '托', + '記': '记', + '訛': '讹', + '訜': '𫍛', + '訝': '讶', + '訞': '𫍚', + '訟': '讼', + '訢': '䜣', + '訣': '诀', + '訥': '讷', + '訨': '𫟞', + '訩': '讻', + '訪': '访', + '設': '设', + '許': '许', + '訴': '诉', + '訶': '诃', + '診': '诊', + '註': '注', + '証': '证', + '詀': '𧮪', + '詁': '诂', + '詆': '诋', + '詊': '𫟟', + '詎': '讵', + '詐': '诈', + '詑': '𫍡', + '詒': '诒', + '詓': '𫍜', + '詔': '诏', + '評': '评', + '詖': '诐', + '詗': '诇', + '詘': '诎', + '詛': '诅', + '詞': '词', + '詠': '咏', + '詡': '诩', + '詢': '询', + '詣': '诣', + '試': '试', + '詩': '诗', + '詫': '诧', + '詬': '诟', + '詭': '诡', + '詮': '诠', + '詰': '诘', + '話': '话', + '該': '该', + '詳': '详', + '詵': '诜', + '詷': '𫍣', + '詼': '诙', + '詿': '诖', + '誂': '𫍥', + '誄': '诔', + '誅': '诛', + '誆': '诓', + '誇': '夸', + '誋': '𫍪', + '誌': '志', + '認': '认', + '誑': '诳', + '誒': '诶', + '誕': '诞', + '誘': '诱', + '誚': '诮', + '語': '语', + '誠': '诚', + '誡': '诫', + '誣': '诬', + '誤': '误', + '誥': '诰', + '誦': '诵', + '誨': '诲', + '說': '说', + '誫': '𫍨', + '説': '说', + '誰': '谁', + '課': '课', + '誳': '𫍮', + '誴': '𫟡', + '誶': '谇', + '誷': '𫍬', + '誹': '诽', + '誺': '𫍧', + '誼': '谊', + '誾': '訚', + '調': '调', + '諂': '谄', + '諄': '谆', + '談': '谈', + '諉': '诿', + '請': '请', + '諍': '诤', + '諏': '诹', + '諑': '诼', + '諒': '谅', + '論': '论', + '諗': '谂', + '諛': '谀', + '諜': '谍', + '諝': '谞', + '諞': '谝', + '諡': '谥', + '諢': '诨', + '諣': '𫍩', + '諤': '谔', + '諥': '𫍳', + '諦': '谛', + '諧': '谐', + '諫': '谏', + '諭': '谕', + '諮': '咨', + '諯': '𫍱', + '諰': '𫍰', + '諱': '讳', + '諳': '谙', + '諴': '𫍯', + '諶': '谌', + '諷': '讽', + '諸': '诸', + '諺': '谚', + '諼': '谖', + '諾': '诺', + '謀': '谋', + '謁': '谒', + '謂': '谓', + '謄': '誊', + '謅': '诌', + '謆': '𫍸', + '謉': '𫍷', + '謊': '谎', + '謎': '谜', + '謏': '𫍲', + '謐': '谧', + '謔': '谑', + '謖': '谡', + '謗': '谤', + '謙': '谦', + '謚': '谥', + '講': '讲', + '謝': '谢', + '謠': '谣', + '謡': '谣', + '謨': '谟', + '謫': '谪', + '謬': '谬', + '謭': '谫', + '謯': '𫍹', + '謱': '𫍴', + '謳': '讴', + '謸': '𫍵', + '謹': '谨', + '謾': '谩', + '譁': '哗', + '譂': '𫟠', + '譅': '䜧', + '譆': '𫍻', + '證': '证', + '譊': '𫍢', + '譎': '谲', + '譏': '讥', + '譑': '𫍤', + '譖': '谮', + '識': '识', + '譙': '谯', + '譚': '谭', + '譜': '谱', + '譞': '𫍽', + '譟': '噪', + '譨': '𫍦', + '譫': '谵', + '譭': '毁', + '譯': '译', + '議': '议', + '譴': '谴', + '護': '护', + '譸': '诪', + '譽': '誉', + '譾': '谫', + '讀': '读', + '讅': '谉', + '變': '变', + '讋': '詟', + '讌': '䜩', + '讎': '雠', + '讒': '谗', + '讓': '让', + '讕': '谰', + '讖': '谶', + '讚': '赞', + '讜': '谠', + '讞': '谳', + '谷': '谷', + '豈': '岂', + '豎': '竖', + '豐': '丰', + '豔': '艳', + '豬': '猪', + '豵': '𫎆', + '豶': '豮', + '貓': '猫', + '貗': '𫎌', + '貙': '䝙', + '貝': '贝', + '貞': '贞', + '貟': '贠', + '負': '负', + '財': '财', + '貢': '贡', + '貧': '贫', + '貨': '货', + '販': '贩', + '貪': '贪', + '貫': '贯', + '責': '责', + '貯': '贮', + '貰': '贳', + '貲': '赀', + '貳': '贰', + '貴': '贵', + '貶': '贬', + '買': '买', + '貸': '贷', + '貺': '贶', + '費': '费', + '貼': '贴', + '貽': '贻', + '貿': '贸', + '賀': '贺', + '賁': '贲', + '賂': '赂', + '賃': '赁', + '賄': '贿', + '賅': '赅', + '資': '资', + '賈': '贾', + '賊': '贼', + '賑': '赈', + '賒': '赊', + '賓': '宾', + '賕': '赇', + '賙': '赒', + '賚': '赉', + '賜': '赐', + '賝': '𫎩', + '賞': '赏', + '賟': '𧹖', + '賠': '赔', + '賡': '赓', + '賢': '贤', + '賣': '卖', + '賤': '贱', + '賦': '赋', + '賧': '赕', + '質': '质', + '賫': '赍', + '賬': '账', + '賭': '赌', + '賰': '䞐', + '賴': '赖', + '賵': '赗', + '賺': '赚', + '賻': '赙', + '購': '购', + '賽': '赛', + '賾': '赜', + '贃': '𧹗', + '贄': '贽', + '贅': '赘', + '贇': '赟', + '贈': '赠', + '贉': '𫎫', + '贊': '赞', + '贋': '赝', + '贍': '赡', + '贏': '赢', + '贐': '赆', + '贑': '𫎬', + '贓': '赃', + '贔': '赑', + '贖': '赎', + '贗': '赝', + '贚': '𫎦', + '贛': '赣', + '贜': '赃', + '赬': '赪', + '趕': '赶', + '趙': '赵', + '趨': '趋', + '趲': '趱', + '跡': '迹', + '踊': '踊', + '踐': '践', + '踰': '逾', + '踴': '踊', + '蹌': '跄', + '蹔': '𫏐', + '蹕': '跸', + '蹟': '迹', + '蹣': '蹒', + '蹤': '踪', + '蹳': '𫏆', + '蹺': '跷', + '蹻': '𫏋', + '躂': '跶', + '躉': '趸', + '躊': '踌', + '躋': '跻', + '躍': '跃', + '躎': '䟢', + '躑': '踯', + '躒': '跞', + '躓': '踬', + '躕': '蹰', + '躘': '𨀁', + '躚': '跹', + '躝': '𨅬', + '躡': '蹑', + '躥': '蹿', + '躦': '躜', + '躪': '躏', + '軀': '躯', + '軉': '𨉗', + '車': '车', + '軋': '轧', + '軌': '轨', + '軍': '军', + '軏': '𫐄', + '軑': '轪', + '軒': '轩', + '軔': '轫', + '軕': '𫐅', + '軗': '𨐅', + '軛': '轭', + '軜': '𫐇', + '軟': '软', + '軤': '轷', + '軨': '𫐉', + '軫': '轸', + '軬': '𫐊', + '軲': '轱', + '軷': '𫐈', + '軸': '轴', + '軹': '轵', + '軺': '轺', + '軻': '轲', + '軼': '轶', + '軾': '轼', + '軿': '𫐌', + '較': '较', + '輄': '𨐈', + '輅': '辂', + '輇': '辁', + '輈': '辀', + '載': '载', + '輊': '轾', + '輋': '𪨶', + '輒': '辄', + '輓': '挽', + '輔': '辅', + '輕': '轻', + '輖': '𫐏', + '輗': '𫐐', + '輛': '辆', + '輜': '辎', + '輝': '辉', + '輞': '辋', + '輟': '辍', + '輢': '𫐎', + '輥': '辊', + '輦': '辇', + '輨': '𫐑', + '輩': '辈', + '輪': '轮', + '輬': '辌', + '輮': '𫐓', + '輯': '辑', + '輳': '辏', + '輷': '𫐒', + '輸': '输', + '輻': '辐', + '輼': '辒', + '輾': '辗', + '輿': '舆', + '轀': '辒', + '轂': '毂', + '轄': '辖', + '轅': '辕', + '轆': '辘', + '轇': '𫐖', + '轉': '转', + '轊': '𫐕', + '轍': '辙', + '轎': '轿', + '轐': '𫐗', + '轔': '辚', + '轗': '𫐘', + '轟': '轰', + '轠': '𫐙', + '轡': '辔', + '轢': '轹', + '轣': '𫐆', + '轤': '轳', + '辟': '辟', + '辦': '办', + '辭': '辞', + '辮': '辫', + '辯': '辩', + '農': '农', + '迴': '回', + '适': '适', + '逕': '迳', + '這': '这', + '連': '连', + '週': '周', + '進': '进', + '遊': '游', + '運': '运', + '過': '过', + '達': '达', + '違': '违', + '遙': '遥', + '遜': '逊', + '遞': '递', + '遠': '远', + '遡': '溯', + '適': '适', + '遱': '𫐷', + '遲': '迟', + '遷': '迁', + '選': '选', + '遺': '遗', + '遼': '辽', + '邁': '迈', + '還': '还', + '邇': '迩', + '邊': '边', + '邏': '逻', + '邐': '逦', + '郁': '郁', + '郟': '郏', + '郵': '邮', + '鄆': '郓', + '鄉': '乡', + '鄒': '邹', + '鄔': '邬', + '鄖': '郧', + '鄟': '𫑘', + '鄧': '邓', + '鄭': '郑', + '鄰': '邻', + '鄲': '郸', + '鄳': '𫑡', + '鄴': '邺', + '鄶': '郐', + '鄺': '邝', + '酇': '酂', + '酈': '郦', + '酸': '酸', + '醃': '腌', + '醖': '酝', + '醜': '丑', + '醞': '酝', + '醟': '蒏', + '醣': '糖', + '醫': '医', + '醬': '酱', + '醱': '酦', + '醶': '𫑷', + '釀': '酿', + '釁': '衅', + '釃': '酾', + '釅': '酽', + '采': '采', + '釋': '释', + '里': '里', + '釐': '厘', + '釒': '钅', + '釓': '钆', + '釔': '钇', + '釕': '钌', + '釗': '钊', + '釘': '钉', + '釙': '钋', + '釚': '𫟲', + '針': '针', + '釟': '𫓥', + '釣': '钓', + '釤': '钐', + '釦': '扣', + '釧': '钏', + '釨': '𫓦', + '釩': '钒', + '釲': '𫟳', + '釳': '𨰿', + '釵': '钗', + '釷': '钍', + '釹': '钕', + '釺': '钎', + '釾': '䥺', + '鈀': '钯', + '鈁': '钫', + '鈃': '钘', + '鈄': '钭', + '鈅': '钥', + '鈆': '𫓪', + '鈇': '𫓧', + '鈈': '钚', + '鈉': '钠', + '鈋': '𨱂', + '鈍': '钝', + '鈎': '钩', + '鈐': '钤', + '鈑': '钣', + '鈒': '钑', + '鈔': '钞', + '鈕': '钮', + '鈖': '𫟴', + '鈗': '𫟵', + '鈛': '𫓨', + '鈞': '钧', + '鈠': '𨱁', + '鈡': '钟', + '鈣': '钙', + '鈥': '钬', + '鈦': '钛', + '鈧': '钪', + '鈮': '铌', + '鈯': '𨱄', + '鈰': '铈', + '鈲': '𨱃', + '鈳': '钶', + '鈴': '铃', + '鈷': '钴', + '鈸': '钹', + '鈹': '铍', + '鈺': '钰', + '鈽': '钸', + '鈾': '铀', + '鈿': '钿', + '鉀': '钾', + '鉁': '𨱅', + '鉅': '巨', + '鉆': '钻', + '鉈': '铊', + '鉉': '铉', + '鉋': '铇', + '鉍': '铋', + '鉑': '铂', + '鉔': '𫓬', + '鉕': '钷', + '鉗': '钳', + '鉚': '铆', + '鉛': '铅', + '鉝': '𫟷', + '鉞': '钺', + '鉠': '𫓭', + '鉢': '钵', + '鉤': '钩', + '鉦': '钲', + '鉬': '钼', + '鉭': '钽', + '鉳': '锫', + '鉶': '铏', + '鉷': '𫟹', + '鉸': '铰', + '鉺': '铒', + '鉻': '铬', + '鉽': '𫟸', + '鉾': '𫓴', + '鉿': '铪', + '銀': '银', + '銁': '𫓲', + '銂': '𫟻', + '銃': '铳', + '銅': '铜', + '銈': '𫓯', + '銊': '𫓰', + '銍': '铚', + '銏': '𫟶', + '銑': '铣', + '銓': '铨', + '銖': '铢', + '銘': '铭', + '銚': '铫', + '銛': '铦', + '銜': '衔', + '銠': '铑', + '銣': '铷', + '銥': '铱', + '銦': '铟', + '銨': '铵', + '銩': '铥', + '銪': '铕', + '銫': '铯', + '銬': '铐', + '銱': '铞', + '銳': '锐', + '銶': '𨱇', + '銷': '销', + '銹': '锈', + '銻': '锑', + '銼': '锉', + '鋁': '铝', + '鋂': '镅', + '鋃': '锒', + '鋅': '锌', + '鋇': '钡', + '鋉': '𨱈', + '鋌': '铤', + '鋏': '铗', + '鋒': '锋', + '鋗': '𫓶', + '鋙': '铻', + '鋝': '锊', + '鋟': '锓', + '鋠': '𫓵', + '鋣': '铘', + '鋤': '锄', + '鋥': '锃', + '鋦': '锔', + '鋨': '锇', + '鋩': '铓', + '鋪': '铺', + '鋭': '锐', + '鋮': '铖', + '鋯': '锆', + '鋰': '锂', + '鋱': '铽', + '鋶': '锍', + '鋸': '锯', + '鋼': '钢', + '錁': '锞', + '錂': '𨱋', + '錄': '录', + '錆': '锖', + '錇': '锫', + '錈': '锩', + '錏': '铔', + '錐': '锥', + '錒': '锕', + '錕': '锟', + '錘': '锤', + '錙': '锱', + '錚': '铮', + '錛': '锛', + '錜': '𫓻', + '錝': '𫓽', + '錟': '锬', + '錠': '锭', + '錡': '锜', + '錢': '钱', + '錤': '𫓹', + '錥': '𫓾', + '錦': '锦', + '錨': '锚', + '錩': '锠', + '錫': '锡', + '錮': '锢', + '錯': '错', + '録': '录', + '錳': '锰', + '錶': '表', + '錸': '铼', + '錼': '镎', + '錽': '𫓸', + '鍀': '锝', + '鍁': '锨', + '鍃': '锪', + '鍄': '𨱉', + '鍅': '钫', + '鍆': '钔', + '鍇': '锴', + '鍈': '锳', + '鍉': '𫔂', + '鍊': '炼', + '鍋': '锅', + '鍍': '镀', + '鍒': '𫔄', + '鍔': '锷', + '鍘': '铡', + '鍚': '钖', + '鍛': '锻', + '鍠': '锽', + '鍤': '锸', + '鍥': '锲', + '鍩': '锘', + '鍬': '锹', + '鍮': '𨱎', + '鍰': '锾', + '鍵': '键', + '鍶': '锶', + '鍺': '锗', + '鍼': '针', + '鍾': '钟', + '鎂': '镁', + '鎄': '锿', + '鎇': '镅', + '鎈': '𫟿', + '鎊': '镑', + '鎌': '镰', + '鎍': '𫔅', + '鎔': '镕', + '鎖': '锁', + '鎘': '镉', + '鎙': '𫔈', + '鎚': '锤', + '鎛': '镈', + '鎝': '𨱏', + '鎞': '𫔇', + '鎡': '镃', + '鎢': '钨', + '鎣': '蓥', + '鎦': '镏', + '鎧': '铠', + '鎩': '铩', + '鎪': '锼', + '鎬': '镐', + '鎭': '镇', + '鎮': '镇', + '鎯': '𨱍', + '鎰': '镒', + '鎲': '镋', + '鎳': '镍', + '鎵': '镓', + '鎷': '𨰾', + '鎸': '镌', + '鎿': '镎', + '鏃': '镞', + '鏆': '𨱌', + '鏇': '镟', + '鏈': '链', + '鏉': '𨱒', + '鏌': '镆', + '鏍': '镙', + '鏐': '镠', + '鏑': '镝', + '鏗': '铿', + '鏘': '锵', + '鏚': '戚', + '鏜': '镗', + '鏝': '镘', + '鏞': '镛', + '鏟': '铲', + '鏡': '镜', + '鏢': '镖', + '鏤': '镂', + '鏥': '𫔊', + '鏦': '𫓩', + '鏨': '錾', + '鏰': '镚', + '鏵': '铧', + '鏷': '镤', + '鏹': '镪', + '鏺': '䥽', + '鏽': '锈', + '鏾': '𫔌', + '鐃': '铙', + '鐄': '𨱑', + '鐇': '𫔍', + '鐈': '𫓱', + '鐋': '铴', + '鐍': '𫔎', + '鐎': '𨱓', + '鐏': '𨱔', + '鐐': '镣', + '鐒': '铹', + '鐓': '镦', + '鐔': '镡', + '鐗': '锏', + '鐘': '钟', + '鐙': '镫', + '鐝': '镢', + '鐠': '镨', + '鐥': '䦅', + '鐦': '锎', + '鐧': '锏', + '鐨': '镄', + '鐪': '𫓺', + '鐫': '镌', + '鐮': '镰', + '鐯': '䦃', + '鐲': '镯', + '鐳': '镭', + '鐵': '铁', + '鐶': '镮', + '鐸': '铎', + '鐺': '铛', + '鐼': '𫔁', + '鐽': '𫟼', + '鐿': '镱', + '鑀': '锿', + '鑄': '铸', + '鑉': '𫠁', + '鑊': '镬', + '鑌': '镔', + '鑑': '鉴', + '鑒': '鉴', + '鑔': '镲', + '鑕': '锧', + '鑞': '镴', + '鑠': '铄', + '鑣': '镳', + '鑥': '镥', + '鑭': '镧', + '鑰': '钥', + '鑱': '镵', + '鑲': '镶', + '鑴': '𫔔', + '鑷': '镊', + '鑹': '镩', + '鑼': '锣', + '鑽': '钻', + '鑾': '銮', + '鑿': '凿', + '钁': '镢', + '钂': '镋', + '镟': '旋', + '長': '长', + '門': '门', + '閂': '闩', + '閃': '闪', + '閆': '闫', + '閈': '闬', + '閉': '闭', + '開': '开', + '閌': '闶', + '閍': '𨸂', + '閎': '闳', + '閏': '闰', + '閐': '𨸃', + '閑': '闲', + '閒': '闲', + '間': '间', + '閔': '闵', + '閗': '𫔯', + '閘': '闸', + '閝': '𫠂', + '閞': '𫔰', + '閡': '阂', + '閣': '阁', + '閤': '合', + '閥': '阀', + '閨': '闺', + '閩': '闽', + '閫': '阃', + '閬': '阆', + '閭': '闾', + '閱': '阅', + '閲': '阅', + '閵': '𫔴', + '閶': '阊', + '閹': '阉', + '閻': '阎', + '閼': '阏', + '閽': '阍', + '閾': '阈', + '閿': '阌', + '闃': '阒', + '闆': '板', + '闇': '暗', + '闈': '闱', + '闊': '阔', + '闋': '阕', + '闌': '阑', + '闍': '阇', + '闐': '阗', + '闑': '𫔶', + '闒': '阘', + '闓': '闿', + '闔': '阖', + '闕': '阙', + '闖': '闯', + '關': '关', + '闞': '阚', + '闠': '阓', + '闡': '阐', + '闢': '辟', + '闤': '阛', + '闥': '闼', + '阪': '阪', + '陘': '陉', + '陝': '陕', + '陞': '升', + '陣': '阵', + '陰': '阴', + '陳': '陈', + '陸': '陆', + '陽': '阳', + '隉': '陧', + '隊': '队', + '階': '阶', + '隕': '陨', + '際': '际', + '隨': '随', + '險': '险', + '隯': '陦', + '隱': '隐', + '隴': '陇', + '隸': '隶', + '隻': '只', + '雇': '雇', + '雋': '隽', + '雕': '雕', + '雖': '虽', + '雙': '双', + '雛': '雏', + '雜': '杂', + '雞': '鸡', + '離': '离', + '難': '难', + '雲': '云', + '電': '电', + '霢': '霡', + '霣': '𫕥', + '霧': '雾', + '霼': '𪵣', + '霽': '霁', + '靂': '雳', + '靄': '霭', + '靆': '叇', + '靈': '灵', + '靉': '叆', + '靚': '靓', + '靜': '静', + '靝': '靔', + '面': '面', + '靦': '腼', + '靧': '𫖃', + '靨': '靥', + '鞀': '鼗', + '鞏': '巩', + '鞝': '绱', + '鞦': '秋', + '鞽': '鞒', + '鞾': '𫖇', + '韁': '缰', + '韃': '鞑', + '韆': '千', + '韉': '鞯', + '韋': '韦', + '韌': '韧', + '韍': '韨', + '韓': '韩', + '韙': '韪', + '韚': '𫠅', + '韛': '𫖔', + '韜': '韬', + '韝': '鞲', + '韞': '韫', + '韠': '𫖒', + '韻': '韵', + '響': '响', + '頁': '页', + '頂': '顶', + '頃': '顷', + '項': '项', + '順': '顺', + '頇': '顸', + '須': '须', + '頊': '顼', + '頌': '颂', + '頍': '𫠆', + '頎': '颀', + '頏': '颃', + '預': '预', + '頑': '顽', + '頒': '颁', + '頓': '顿', + '頗': '颇', + '領': '领', + '頜': '颌', + '頡': '颉', + '頤': '颐', + '頦': '颏', + '頫': '𫖯', + '頭': '头', + '頮': '颒', + '頰': '颊', + '頲': '颋', + '頴': '颕', + '頵': '𫖳', + '頷': '颔', + '頸': '颈', + '頹': '颓', + '頻': '频', + '頽': '颓', + '顂': '𩓋', + '顃': '𩖖', + '顅': '𫖶', + '顆': '颗', + '題': '题', + '額': '额', + '顎': '颚', + '顏': '颜', + '顒': '颙', + '顓': '颛', + '顔': '颜', + '顗': '𫖮', + '願': '愿', + '顙': '颡', + '顛': '颠', + '類': '类', + '顢': '颟', + '顣': '𫖹', + '顥': '颢', + '顧': '顾', + '顫': '颤', + '顬': '颥', + '顯': '显', + '顰': '颦', + '顱': '颅', + '顳': '颞', + '顴': '颧', + '風': '风', + '颭': '飐', + '颮': '飑', + '颯': '飒', + '颰': '𩙥', + '颱': '台', + '颳': '刮', + '颶': '飓', + '颷': '𩙪', + '颸': '飔', + '颺': '飏', + '颻': '飖', + '颼': '飕', + '颾': '𩙫', + '飀': '飗', + '飄': '飘', + '飆': '飙', + '飈': '飚', + '飋': '𫗋', + '飛': '飞', + '飠': '饣', + '飢': '饥', + '飣': '饤', + '飥': '饦', + '飦': '𫗞', + '飩': '饨', + '飪': '饪', + '飫': '饫', + '飭': '饬', + '飯': '饭', + '飱': '飧', + '飲': '饮', + '飴': '饴', + '飵': '𫗢', + '飶': '𫗣', + '飼': '饲', + '飽': '饱', + '飾': '饰', + '飿': '饳', + '餃': '饺', + '餄': '饸', + '餅': '饼', + '餉': '饷', + '養': '养', + '餌': '饵', + '餎': '饹', + '餏': '饻', + '餑': '饽', + '餒': '馁', + '餓': '饿', + '餔': '𫗦', + '餕': '馂', + '餖': '饾', + '餗': '𫗧', + '餘': '余', + '餚': '肴', + '餛': '馄', + '餜': '馃', + '餞': '饯', + '餡': '馅', + '餦': '𫗠', + '餧': '𫗪', + '館': '馆', + '餪': '𫗬', + '餫': '𫗥', + '餬': '糊', + '餭': '𫗮', + '餱': '糇', + '餳': '饧', + '餵': '喂', + '餶': '馉', + '餷': '馇', + '餸': '𩠌', + '餺': '馎', + '餼': '饩', + '餾': '馏', + '餿': '馊', + '饁': '馌', + '饃': '馍', + '饅': '馒', + '饈': '馐', + '饉': '馑', + '饊': '馓', + '饋': '馈', + '饌': '馔', + '饑': '饥', + '饒': '饶', + '饗': '飨', + '饘': '𫗴', + '饜': '餍', + '饞': '馋', + '饟': '𫗵', + '饠': '𫗩', + '饢': '馕', + '馬': '马', + '馭': '驭', + '馮': '冯', + '馯': '𫘛', + '馱': '驮', + '馳': '驰', + '馴': '驯', + '馹': '驲', + '馼': '𫘜', + '駁': '驳', + '駃': '𫘝', + '駊': '𫘟', + '駎': '𩧨', + '駐': '驻', + '駑': '驽', + '駒': '驹', + '駔': '驵', + '駕': '驾', + '駘': '骀', + '駙': '驸', + '駚': '𩧫', + '駛': '驶', + '駝': '驼', + '駞': '𫘞', + '駟': '驷', + '駡': '骂', + '駢': '骈', + '駤': '𫘠', + '駧': '𩧲', + '駩': '𩧴', + '駫': '𫘡', + '駭': '骇', + '駰': '骃', + '駱': '骆', + '駶': '𩧺', + '駸': '骎', + '駻': '𫘣', + '駿': '骏', + '騁': '骋', + '騂': '骍', + '騃': '𫘤', + '騄': '𫘧', + '騅': '骓', + '騉': '𫘥', + '騊': '𫘦', + '騌': '骔', + '騍': '骒', + '騎': '骑', + '騏': '骐', + '騔': '𩨀', + '騖': '骛', + '騙': '骗', + '騚': '𩨊', + '騜': '𫘩', + '騝': '𩨃', + '騟': '𩨈', + '騠': '𫘨', + '騤': '骙', + '騧': '䯄', + '騪': '𩨄', + '騫': '骞', + '騭': '骘', + '騮': '骝', + '騰': '腾', + '騱': '𫘬', + '騴': '𫘫', + '騵': '𫘪', + '騶': '驺', + '騷': '骚', + '騸': '骟', + '騻': '𫘭', + '騼': '𫠋', + '騾': '骡', + '驀': '蓦', + '驁': '骜', + '驂': '骖', + '驃': '骠', + '驄': '骢', + '驅': '驱', + '驊': '骅', + '驋': '𩧯', + '驌': '骕', + '驍': '骁', + '驏': '骣', + '驓': '𫘯', + '驕': '骄', + '驗': '验', + '驙': '𫘰', + '驚': '惊', + '驛': '驿', + '驟': '骤', + '驢': '驴', + '驤': '骧', + '驥': '骥', + '驦': '骦', + '驨': '𫘱', + '驪': '骊', + '驫': '骉', + '骯': '肮', + '髏': '髅', + '髒': '脏', + '體': '体', + '髕': '髌', + '髖': '髋', + '髮': '发', + '鬆': '松', + '鬍': '胡', + '鬖': '𩭹', + '鬚': '须', + '鬠': '𫘽', + '鬢': '鬓', + '鬥': '斗', + '鬧': '闹', + '鬨': '哄', + '鬩': '阋', + '鬮': '阄', + '鬱': '郁', + '鬹': '鬶', + '魎': '魉', + '魘': '魇', + '魚': '鱼', + '魛': '鱽', + '魟': '𫚉', + '魢': '鱾', + '魥': '𩽹', + '魦': '𫚌', + '魨': '鲀', + '魯': '鲁', + '魴': '鲂', + '魵': '𫚍', + '魷': '鱿', + '魺': '鲄', + '魽': '𫠐', + '鮁': '鲅', + '鮃': '鲆', + '鮄': '𫚒', + '鮅': '𫚑', + '鮆': '𫚖', + '鮊': '鲌', + '鮋': '鲉', + '鮍': '鲏', + '鮎': '鲇', + '鮐': '鲐', + '鮑': '鲍', + '鮒': '鲋', + '鮓': '鲊', + '鮕': '𩾀', + '鮚': '鲒', + '鮜': '鲘', + '鮝': '鲞', + '鮞': '鲕', + '鮟': '𩽾', + '鮣': '䲟', + '鮤': '𫚓', + '鮦': '鲖', + '鮪': '鲔', + '鮫': '鲛', + '鮭': '鲑', + '鮮': '鲜', + '鮯': '𫚗', + '鮰': '𫚔', + '鮳': '鲓', + '鮵': '𫚛', + '鮶': '鲪', + '鮸': '𩾃', + '鮺': '鲝', + '鮿': '𫚚', + '鯀': '鲧', + '鯁': '鲠', + '鯄': '𩾁', + '鯆': '𫚙', + '鯇': '鲩', + '鯉': '鲤', + '鯊': '鲨', + '鯒': '鲬', + '鯔': '鲻', + '鯕': '鲯', + '鯖': '鲭', + '鯗': '鲞', + '鯛': '鲷', + '鯝': '鲴', + '鯞': '𫚡', + '鯡': '鲱', + '鯢': '鲵', + '鯤': '鲲', + '鯧': '鲳', + '鯨': '鲸', + '鯪': '鲮', + '鯫': '鲰', + '鯬': '𫚞', + '鯰': '鲶', + '鯱': '𩾇', + '鯴': '鲺', + '鯶': '𩽼', + '鯷': '鳀', + '鯽': '鲫', + '鯾': '𫚣', + '鯿': '鳊', + '鰁': '鳈', + '鰂': '鲗', + '鰃': '鳂', + '鰆': '䲠', + '鰈': '鲽', + '鰉': '鳇', + '鰋': '𫚢', + '鰌': '䲡', + '鰍': '鳅', + '鰏': '鲾', + '鰐': '鳄', + '鰑': '𫚊', + '鰒': '鳆', + '鰓': '鳃', + '鰕': '𫚥', + '鰛': '鳁', + '鰜': '鳒', + '鰟': '鳑', + '鰠': '鳋', + '鰣': '鲥', + '鰤': '𫚕', + '鰥': '鳏', + '鰦': '𫚤', + '鰧': '䲢', + '鰨': '鳎', + '鰩': '鳐', + '鰫': '𫚦', + '鰭': '鳍', + '鰮': '鳁', + '鰱': '鲢', + '鰲': '鳌', + '鰳': '鳓', + '鰵': '鳘', + '鰷': '鲦', + '鰹': '鲣', + '鰺': '鲹', + '鰻': '鳗', + '鰼': '鳛', + '鰽': '𫚧', + '鰾': '鳔', + '鱂': '鳉', + '鱄': '𫚋', + '鱅': '鳙', + '鱆': '𫠒', + '鱇': '𩾌', + '鱈': '鳕', + '鱉': '鳖', + '鱊': '𫚪', + '鱒': '鳟', + '鱔': '鳝', + '鱖': '鳜', + '鱗': '鳞', + '鱘': '鲟', + '鱝': '鲼', + '鱟': '鲎', + '鱠': '鲙', + '鱢': '𫚫', + '鱣': '鳣', + '鱤': '鳡', + '鱧': '鳢', + '鱨': '鲿', + '鱭': '鲚', + '鱮': '𫚈', + '鱯': '鳠', + '鱲': '𫚭', + '鱷': '鳄', + '鱸': '鲈', + '鱺': '鲡', + '鳥': '鸟', + '鳧': '凫', + '鳩': '鸠', + '鳬': '凫', + '鳲': '鸤', + '鳳': '凤', + '鳴': '鸣', + '鳶': '鸢', + '鳷': '𫛛', + '鳼': '𪉃', + '鳽': '𫛚', + '鳾': '䴓', + '鴀': '𫛜', + '鴃': '𫛞', + '鴅': '𫛝', + '鴆': '鸩', + '鴇': '鸨', + '鴉': '鸦', + '鴐': '𫛤', + '鴒': '鸰', + '鴔': '𫛡', + '鴕': '鸵', + '鴗': '𫁡', + '鴛': '鸳', + '鴜': '𪉈', + '鴝': '鸲', + '鴞': '鸮', + '鴟': '鸱', + '鴣': '鸪', + '鴥': '𫛣', + '鴦': '鸯', + '鴨': '鸭', + '鴮': '𫛦', + '鴯': '鸸', + '鴰': '鸹', + '鴲': '𪉆', + '鴳': '𫛩', + '鴴': '鸻', + '鴷': '䴕', + '鴻': '鸿', + '鴽': '𫛪', + '鴿': '鸽', + '鵁': '䴔', + '鵂': '鸺', + '鵃': '鸼', + '鵊': '𫛥', + '鵐': '鹀', + '鵑': '鹃', + '鵒': '鹆', + '鵓': '鹁', + '鵚': '𪉍', + '鵜': '鹈', + '鵝': '鹅', + '鵟': '𫛭', + '鵠': '鹄', + '鵡': '鹉', + '鵧': '𫛨', + '鵩': '𫛳', + '鵪': '鹌', + '鵫': '𫛱', + '鵬': '鹏', + '鵮': '鹐', + '鵯': '鹎', + '鵰': '雕', + '鵲': '鹊', + '鵷': '鹓', + '鵾': '鹍', + '鶄': '䴖', + '鶇': '鸫', + '鶉': '鹑', + '鶊': '鹒', + '鶌': '𫛵', + '鶒': '𫛶', + '鶓': '鹋', + '鶖': '鹙', + '鶗': '𫛸', + '鶘': '鹕', + '鶚': '鹗', + '鶡': '鹖', + '鶥': '鹛', + '鶦': '𫛷', + '鶩': '鹜', + '鶪': '䴗', + '鶬': '鸧', + '鶭': '𫛯', + '鶯': '莺', + '鶰': '𫛫', + '鶲': '鹟', + '鶴': '鹤', + '鶹': '鹠', + '鶺': '鹡', + '鶻': '鹘', + '鶼': '鹣', + '鶿': '鹚', + '鷀': '鹚', + '鷁': '鹢', + '鷂': '鹞', + '鷄': '鸡', + '鷅': '𫛽', + '鷈': '䴘', + '鷉': '䴘', + '鷊': '鹝', + '鷐': '𫜀', + '鷓': '鹧', + '鷔': '𪉑', + '鷖': '鹥', + '鷗': '鸥', + '鷙': '鸷', + '鷚': '鹨', + '鷣': '𫜃', + '鷤': '𫛴', + '鷥': '鸶', + '鷦': '鹪', + '鷨': '𪉊', + '鷩': '𫜁', + '鷫': '鹔', + '鷯': '鹩', + '鷲': '鹫', + '鷳': '鹇', + '鷴': '鹇', + '鷷': '𫜄', + '鷸': '鹬', + '鷹': '鹰', + '鷺': '鹭', + '鷽': '鸴', + '鷿': '䴙', + '鸂': '㶉', + '鸇': '鹯', + '鸊': '䴙', + '鸋': '𫛢', + '鸌': '鹱', + '鸏': '鹲', + '鸕': '鸬', + '鸗': '𫛟', + '鸘': '鹴', + '鸚': '鹦', + '鸛': '鹳', + '鸝': '鹂', + '鸞': '鸾', + '鹵': '卤', + '鹹': '咸', + '鹺': '鹾', + '鹼': '碱', + '鹽': '盐', + '麗': '丽', + '麥': '麦', + '麨': '𪎊', + '麩': '麸', + '麪': '面', + '麫': '面', + '麬': '𤿲', + '麯': '曲', + '麲': '𪎉', + '麳': '𪎌', + '麴': '曲', + '麵': '面', + '麷': '𫜑', + '麼': '么', + '麽': '么', + '黃': '黄', + '黌': '黉', + '點': '点', + '黨': '党', + '黲': '黪', + '黴': '霉', + '黶': '黡', + '黷': '黩', + '黽': '黾', + '黿': '鼋', + '鼂': '鼌', + '鼉': '鼍', + '鼕': '冬', + '鼴': '鼹', + '齇': '齄', + '齊': '齐', + '齋': '斋', + '齎': '赍', + '齏': '齑', + '齒': '齿', + '齔': '龀', + '齕': '龁', + '齗': '龂', + '齙': '龅', + '齜': '龇', + '齟': '龃', + '齠': '龆', + '齡': '龄', + '齣': '出', + '齦': '龈', + '齧': '啮', + '齩': '𫜪', + '齪': '龊', + '齬': '龉', + '齭': '𫜭', + '齯': '𫠜', + '齰': '𫜬', + '齲': '龋', + '齴': '𫜮', + '齶': '腭', + '齷': '龌', + '齾': '𫜰', + '龍': '龙', + '龎': '厐', + '龐': '庞', + '龑': '䶮', + '龓': '𫜲', + '龔': '龚', + '龕': '龛', + '龜': '龟', + '龭': '𩨎', + '龯': '𨱆', + '鿁': '䜤', + '𠁞': '𠀾', + '𠌥': '𠆿', + '𠏢': '𠉗', + '𠐊': '𫝋', + '𠗣': '㓆', + '𠞆': '𠛆', + '𠠎': '𠚳', + '𠬙': '𪠡', + '𠽃': '𪠺', + '𠿕': '𪜎', + '𡂡': '𪢒', + '𡃄': '𪡺', + '𡃕': '𠴛', + '𡃤': '𪢐', + '𡄔': '𠴢', + '𡄣': '𠵸', + '𡅏': '𠲥', + '𡅯': '𪢖', + '𡑭': '𡋗', + '𡓁': '𪤄', + '𡓾': '𡋀', + '𡔖': '𡍣', + '𡞵': '㛟', + '𡟫': '𫝪', + '𡠹': '㛿', + '𡡎': '𡞱', + '𡢃': '㛠', + '𡮉': '𡭜', + '𡮣': '𡭬', + '𡳳': '𡳃', + '𡸗': '𪨩', + '𡹬': '𪨹', + '𡻕': '岁', + '𡽗': '𡸃', + '𡾱': '㟜', + '𡿖': '𪩛', + '𢍰': '𪪴', + '𢠼': '𢙑', + '𢣐': '𪬚', + '𢣚': '𢘝', + '𢣭': '𢘞', + '𢤩': '𪫡', + '𢤱': '𢘙', + '𢤿': '𪬯', + '𢯷': '𪭝', + '𢶒': '𪭯', + '𢶫': '𢫞', + '𢷬': '𢭏', + '𢷮': '𢫊', + '𢹿': '𢬦', + '𢺳': '𪮳', + '𣈶': '暅', + '𣋋': '𣈣', + '𣍐': '𠊉', + '𣙎': '㭣', + '𣜬': '𪳗', + '𣝕': '𣘷', + '𣞻': '𣘓', + '𣠩': '𣞎', + '𣠲': '𣑶', + '𣯩': '𣯣', + '𣯴': '𣭤', + '𣯶': '毶', + '𣽏': '𪶮', + '𣾷': '㳢', + '𣿉': '𣶫', + '𤁣': '𣺽', + '𤄷': '𪶒', + '𤅶': '𣷷', + '𤑳': '𤎻', + '𤑹': '𪹀', + '𤒎': '𤊀', + '𤒻': '𪹹', + '𤓌': '𪹠', + '𤓩': '𤊰', + '𤘀': '𪺣', + '𤛮': '𤙯', + '𤛱': '𫞢', + '𤜆': '𪺪', + '𤠮': '𪺸', + '𤢟': '𤝢', + '𤢻': '𢢐', + '𤩂': '𫞧', + '𤪺': '㻘', + '𤫩': '㻏', + '𤬅': '𪼴', + '𤳷': '𪽝', + '𤳸': '𤳄', + '𤷃': '𪽭', + '𤸫': '𤶧', + '𤺔': '𪽴', + '𥊝': '𥅿', + '𥌃': '𥅘', + '𥏝': '𪿊', + '𥕥': '𥐰', + '𥖅': '𥐯', + '𥖲': '𪿞', + '𥗇': '𪿵', + '𥜐': '𫀓', + '𥜰': '𫀌', + '𥞵': '𥞦', + '𥢢': '䅪', + '𥢶': '𫞷', + '𥢷': '𫀮', + '𥨐': '𥧂', + '𥪂': '𥩺', + '𥯤': '𫁳', + '𥴨': '𫂖', + '𥴼': '𫁺', + '𥵃': '𥱔', + '𥵊': '𥭉', + '𥶽': '𫁱', + '𥸠': '𥮋', + '𥻦': '𫂿', + '𥼽': '𥹥', + '𥽖': '𥺇', + '𥾯': '𫄝', + '𥿊': '𦈈', + '𦀖': '𫄦', + '𦂅': '𦈒', + '𦃄': '𦈗', + '𦃩': '𫄯', + '𦅇': '𫄪', + '𦅈': '𫄵', + '𦆲': '𫟇', + '𦒀': '𫅥', + '𦔖': '𫅼', + '𦘧': '𡳒', + '𦟼': '𫆝', + '𦠅': '𫞅', + '𦡝': '𫆫', + '𦢈': '𣍨', + '𦣎': '𦟗', + '𦧺': '𫇘', + '𦪙': '䑽', + '𦪽': '𦨩', + '𦱌': '𫇪', + '𦾟': '𦶻', + '𧎈': '𧌥', + '𧒯': '𫊹', + '𧔥': '𧒭', + '𧕟': '𧉐', + '𧜗': '䘞', + '𧜵': '䙊', + '𧝞': '䘛', + '𧞫': '𫌋', + '𧟀': '𧝧', + '𧡴': '𫌫', + '𧢄': '𫌬', + '𧦝': '𫍞', + '𧦧': '𫍟', + '𧩕': '𫍭', + '𧩙': '䜥', + '𧩼': '𫍶', + '𧫝': '𫍺', + '𧬤': '𫍼', + '𧭈': '𫍾', + '𧭹': '𫍐', + '𧳟': '𧳕', + '𧵳': '䞌', + '𧶔': '𧹓', + '𧶧': '䞎', + '𧷎': '𪠀', + '𧸘': '𫎨', + '𧹈': '𪥠', + '𧽯': '𫎸', + '𨂐': '𫏌', + '𨄣': '𨀱', + '𨅍': '𨁴', + '𨆪': '𫏕', + '𨇁': '𧿈', + '𨇞': '𨅫', + '𨇤': '𫏨', + '𨇰': '𫏞', + '𨇽': '𫏑', + '𨈊': '𨂺', + '𨈌': '𨄄', + '𨊰': '䢀', + '𨊸': '䢁', + '𨊻': '𨐆', + '𨋢': '䢂', + '𨌈': '𫐍', + '𨍰': '𫐔', + '𨎌': '𫐋', + '𨎮': '𨐉', + '𨏠': '𨐇', + '𨏥': '𨐊', + '𨞺': '𫟫', + '𨟊': '𫟬', + '𨢿': '𨡙', + '𨣈': '𨡺', + '𨣞': '𨟳', + '𨣧': '𨠨', + '𨤻': '𨤰', + '𨥛': '𨱀', + '𨥟': '𫓫', + '𨦫': '䦀', + '𨧜': '䦁', + '𨧰': '𫟽', + '𨧱': '𨱊', + '𨨛': '𫓼', + '𨨢': '𫓿', + '𨩰': '𫟾', + '𨪕': '𫓮', + '𨫒': '𨱐', + '𨬖': '𫔏', + '𨭖': '𫔑', + '𨭸': '𫔐', + '𨮂': '𨱕', + '𨮳': '𫔒', + '𨯅': '䥿', + '𨯟': '𫔓', + '𨰃': '𫔉', + '𨰋': '𫓳', + '𨰥': '𫔕', + '𨰲': '𫔃', + '𨲳': '𫔖', + '𨳑': '𨸁', + '𨳕': '𨸀', + '𨴗': '𨸅', + '𨴹': '𫔲', + '𨵩': '𨸆', + '𨵸': '𨸇', + '𨶀': '𨸉', + '𨶏': '𨸊', + '𨶮': '𨸌', + '𨶲': '𨸋', + '𨷲': '𨸎', + '𨼳': '𫔽', + '𨽏': '𨸘', + '𩀨': '𫕚', + '𩅙': '𫕨', + '𩎖': '𫖑', + '𩎢': '𩏾', + '𩏂': '𫖓', + '𩏠': '𫖖', + '𩏪': '𩏽', + '𩏷': '𫃗', + '𩑔': '𫖪', + '𩒎': '𫖭', + '𩓣': '𩖕', + '𩓥': '𫖵', + '𩔑': '𫖷', + '𩔳': '𫖴', + '𩖰': '𫠇', + '𩗀': '𩙦', + '𩗓': '𫗈', + '𩗴': '𫗉', + '𩘀': '𩙩', + '𩘝': '𩙭', + '𩘹': '𩙨', + '𩘺': '𩙬', + '𩙈': '𩙰', + '𩚛': '𩟿', + '𩚥': '𩠀', + '𩚩': '𫗡', + '𩚵': '𩠁', + '𩛆': '𩠂', + '𩛌': '𫗤', + '𩛡': '𫗨', + '𩛩': '𩠃', + '𩜇': '𩠉', + '𩜦': '𩠆', + '𩜵': '𩠊', + '𩝔': '𩠋', + '𩝽': '𫗳', + '𩞄': '𩠎', + '𩞦': '𩠏', + '𩞯': '䭪', + '𩟐': '𩠅', + '𩟗': '𫗚', + '𩠴': '𩠠', + '𩡣': '𩡖', + '𩡺': '𩧦', + '𩢡': '𩧬', + '𩢴': '𩧵', + '𩢸': '𩧳', + '𩢾': '𩧮', + '𩣏': '𩧶', + '𩣑': '䯃', + '𩣫': '𩧸', + '𩣵': '𩧻', + '𩣺': '𩧼', + '𩤊': '𩧩', + '𩤙': '𩨆', + '𩤲': '𩨉', + '𩤸': '𩨅', + '𩥄': '𩨋', + '𩥇': '𩨍', + '𩥉': '𩧱', + '𩥑': '𩨌', + '𩦠': '𫠌', + '𩧆': '𩨐', + '𩭙': '𩬣', + '𩯁': '𫙂', + '𩯳': '𩯒', + '𩰀': '𩬤', + '𩰹': '𩰰', + '𩳤': '𩲒', + '𩴵': '𩴌', + '𩵦': '𫠏', + '𩵩': '𩽺', + '𩵹': '𩽻', + '𩶁': '𫚎', + '𩶘': '䲞', + '𩶰': '𩽿', + '𩶱': '𩽽', + '𩷰': '𩾄', + '𩸃': '𩾅', + '𩸄': '𫚝', + '𩸡': '𫚟', + '𩸦': '𩾆', + '𩻗': '𫚨', + '𩻬': '𫚩', + '𩻮': '𫚘', + '𩼶': '𫚬', + '𩽇': '𩾎', + '𩿅': '𫠖', + '𩿤': '𫛠', + '𩿪': '𪉄', + '𪀖': '𫛧', + '𪀦': '𪉅', + '𪀾': '𪉋', + '𪁈': '𪉉', + '𪁖': '𪉌', + '𪂆': '𪉎', + '𪃍': '𪉐', + '𪃏': '𪉏', + '𪃒': '𫛻', + '𪃧': '𫛹', + '𪄆': '𪉔', + '𪄕': '𪉒', + '𪅂': '𫜂', + '𪆷': '𫛾', + '𪇳': '𪉕', + '𪈼': '𪉓', + '𪉸': '𫜊', + '𪋿': '𪎍', + '𪌭': '𫜓', + '𪍠': '𫜕', + '𪓰': '𫜟', + '𪔵': '𪔭', + '𪘀': '𪚏', + '𪘯': '𪚐', + '𪙏': '𫜯', + '𪟖': '𠛾', + '𪷓': '𣶭', + '𫒡': '𫓷', + '𫜦': '𫜫', +}