mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 01:55:35 +08:00
update book code
This commit is contained in:
43
eBook/examples/chapter_11/print.go
Normal file
43
eBook/examples/chapter_11/print.go
Normal file
@@ -0,0 +1,43 @@
|
||||
// print.go
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type Stringer interface {
|
||||
String() string
|
||||
}
|
||||
|
||||
type Celsius float64
|
||||
|
||||
func (c Celsius) String() string {
|
||||
return strconv.FormatFloat(float64(c),'f', 1, 64) + " °C"
|
||||
}
|
||||
|
||||
type Day int
|
||||
|
||||
var dayName = []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
|
||||
|
||||
func (day Day) String() string {
|
||||
return dayName[day]
|
||||
}
|
||||
|
||||
func print(args ...interface{}) {
|
||||
for i, arg := range args {
|
||||
if i > 0 {os.Stdout.WriteString(" ")}
|
||||
switch a := arg.(type) { // type switch
|
||||
case Stringer: os.Stdout.WriteString(a.String())
|
||||
case int: os.Stdout.WriteString(strconv.Itoa(a))
|
||||
case string: os.Stdout.WriteString(a)
|
||||
// more types
|
||||
default: os.Stdout.WriteString("???")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
print(Day(1), "was", Celsius(18.36)) // Tuesday was 18.4 °C
|
||||
}
|
||||
// Tuesday was 18.4 °C
|
Reference in New Issue
Block a user