如果你熟悉面向?qū)ο缶幊?,你可能?huì)將這兩種方式當(dāng)作是subtype polymorphism(子類(lèi)型多態(tài))和 ad hoc polymorphism(非參數(shù)多態(tài)),但是你不需要去記住這些術(shù)語(yǔ)。對(duì)于本章剩下的部分,我們將會(huì)呈現(xiàn)一些第二種方式的例子。
import "database/sql"
func listTracks(db sql.DB, artist string, minYear, maxYear int) {
result, err := db.Exec(
"SELECT * FROM tracks WHERE artist = ? AND ? <= year AND year <= ?",
artist, minYear, maxYear)
// ...
}
func sqlQuote(x interface{}) string {
if x == nil {
return "NULL"
} else if _, ok := x.(int); ok {
return fmt.Sprintf("%d", x)
} else if _, ok := x.(uint); ok {
return fmt.Sprintf("%d", x)
} else if b, ok := x.(bool); ok {
if b {
return "TRUE"
}
return "FALSE"
} else if s, ok := x.(string); ok {
return sqlQuoteString(s) // (not shown)
} else {
panic(fmt.Sprintf("unexpected type %T: %v", x, x))
}
}
在最簡(jiǎn)單的形式中,一個(gè)類(lèi)型分支像普通的switch語(yǔ)句一樣,它的運(yùn)算對(duì)象是x.(type)——它使用了關(guān)鍵詞字面量type——并且每個(gè)case有一到多個(gè)類(lèi)型。一個(gè)類(lèi)型分支基于這個(gè)接口值的動(dòng)態(tài)類(lèi)型使一個(gè)多路分支有效。這個(gè)nil的case和if x == nil匹配,并且這個(gè)default的case和如果其它c(diǎn)ase都不匹配的情況匹配。一個(gè)對(duì)sqlQuote的類(lèi)型分支可能會(huì)有這些case:
switch x.(type) {
case nil: // ...
case int, uint: // ...
case bool: // ...
case string: // ...
default: // ...
}
func sqlQuote(x interface{}) string {
switch x := x.(type) {
case nil:
return "NULL"
case int, uint:
return fmt.Sprintf("%d", x) // x has type interface{} here.
case bool:
if x {
return "TRUE"
}
return "FALSE"
case string:
return sqlQuoteString(x) // (not shown)
default:
panic(fmt.Sprintf("unexpected type %T: %v", x, x))
}
}
更多建議: