gopl-zh.github.com/ch5/ch5-05.md

133 lines
4.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

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

## 5.5. 函數值
在Go中函數被看作第一類值first-class values函數像其他值一樣擁有類型可以被賦值給其他變量傳遞給函數從函數返迴。對函數值function value的調用類似函數調用。例子如下
```Go
func square(n int) int { return n * n }
func negative(n int) int { return -n }
func product(m, n int) int { return m * n }
f := square
fmt.Println(f(3)) // "9"
f = negative
fmt.Println(f(3)) // "-3"
fmt.Printf("%T\n", f) // "func(int) int"
f = product // compile error: can't assign func(int, int) int to func(int) int
```
函數類型的零值是nil。調用值爲nil的函數值會引起panic錯誤
```Go
var f func(int) int
f(3) // 此處f的值爲nil, 會引起panic錯誤
```
函數值可以與nil比較
```Go
var f func(int) int
if f != nil {
f(3)
}
```
但是函數值之間是不可比較的也不能用函數值作爲map的key。
函數值使得我們不僅僅可以通過數據來參數化函數亦可通過行爲。標準庫中包含許多這樣的例子。下面的代碼展示了如何使用這個技巧。strings.Map對字符串中的每個字符調用add1函數併將每個add1函數的返迴值組成一個新的字符串返迴給調用者。
```Go
func add1(r rune) rune { return r + 1 }
fmt.Println(strings.Map(add1, "HAL-9000")) // "IBM.:111"
fmt.Println(strings.Map(add1, "VMS")) // "WNT"
fmt.Println(strings.Map(add1, "Admix")) // "Benjy"
```
5.2節的findLinks函數使用了輔助函數visit,遍歷和操作了HTML頁面的所有結點。使用函數值我們可以將遍歷結點的邏輯和操作結點的邏輯分離使得我們可以複用遍歷的邏輯從而對結點進行不同的操作。
```Go
gopl.io/ch5/outline2
// forEachNode針對每個結點x,都會調用pre(x)和post(x)。
// pre和post都是可選的。
// 遍歷孩子結點之前,pre被調用
// 遍歷孩子結點之後post被調用
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)
}
}
```
該函數接收2個函數作爲參數分别在結點的孩子被訪問前和訪問後調用。這樣的設計給調用者更大的靈活性。舉個例子現在我們有startElemen和endElement兩個函數用於輸出HTML元素的開始標籤和結束標籤`<b>...</b>`
```Go
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</%s>\n", depth*2, "", n.Data)
}
}
```
上面的代碼利用fmt.Printf的一個小技巧控製輸出的縮進。`%*s`中的`*`會在字符串之前填充一些空格。在例子中,每次輸出會先填充`depth*2`數量的空格,再輸出""最後再輸出HTML標籤。
如果我們像下面這樣調用forEachNode
```Go
forEachNode(doc, startElement, endElement)
```
與之前的outline程序相比我們得到了更加詳細的頁面結構
```
$ go build gopl.io/ch5/outline2
$ ./outline2 http://gopl.io
<html>
<head>
<meta>
</meta>
<title>
</title>
<style>
</style>
</head>
<body>
<table>
<tbody>
<tr>
<td>
<a>
<img>
</img>
...
```
**練習 5.7** 完善startElement和endElement函數使其成爲通用的HTML輸出器。要求輸出註釋結點文本結點以及每個元素的屬性< a href='...'>)。使用簡略格式輸出沒有孩子結點的元素(卽用`<img/>`代替`<img></img>`。編寫測試驗證程序輸出的格式正確。詳見11章
**練習 5.8** 脩改pre和post函數使其返迴布爾類型的返迴值。返迴false時中止forEachNoded的遍歷。使用脩改後的代碼編寫ElementByID函數根據用戶輸入的id査找第一個擁有該id元素的HTML元素査找成功後停止遍歷。
```Go
func ElementByID(doc *html.Node, id string) *html.Node
```
**練習 5.9** 編寫函數expand將s中的"foo"替換爲f("foo")的返迴值。
```Go
func expand(s string, f func(string) string) string
```