fix: coding style and file format for chapter 10.

This commit is contained in:
Bo-Yi Wu
2017-02-11 12:28:43 +08:00
parent d9041c7fc3
commit ca79293078
19 changed files with 731 additions and 720 deletions

View File

@@ -3,13 +3,13 @@ package main
import "fmt" import "fmt"
type C struct { type C struct {
x float32; x float32
int; int
string; string
} }
func main() { func main() {
c := C{3.14, 7, "hello"} c := C{3.14, 7, "hello"}
fmt.Println(c.x, c.int, c.string) // output: 3.14 7 hello fmt.Println(c.x, c.int, c.string) // output: 3.14 7 hello
fmt.Println(c) // output: {3.14 7 hello} fmt.Println(c) // output: {3.14 7 hello}
} }

View File

@@ -9,11 +9,12 @@ import (
type Celsius float64 type Celsius float64
func (c Celsius) String() string { func (c Celsius) String() string {
return "The temperature is: " + strconv.FormatFloat(float64(c),'f', 1, 32) + " °C" return "The temperature is: " + strconv.FormatFloat(float64(c), 'f', 1, 32) + " °C"
} }
func main() { func main() {
var c Celsius = 18.36 var c Celsius = 18.36
fmt.Println(c) fmt.Println(c)
} }
// The temperature is: 18.4 °C // The temperature is: 18.4 °C

View File

@@ -5,13 +5,13 @@ import "fmt"
type Day int type Day int
const ( const (
MO Day = iota MO Day = iota
TU TU
WE WE
TH TH
FR FR
SA SA
SU SU
) )
var dayName = []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"} var dayName = []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
@@ -21,14 +21,15 @@ func (day Day) String() string {
} }
func main() { func main() {
var th Day = 3 var th Day = 3
fmt.Printf("The 3rd day is: %s\n", th) fmt.Printf("The 3rd day is: %s\n", th)
// If index > 6: panic: runtime error: index out of range // If index > 6: panic: runtime error: index out of range
// but use the enumerated type to work with valid values: // but use the enumerated type to work with valid values:
var day = SU; var day = SU
fmt.Println(day); // prints Sunday fmt.Println(day) // prints Sunday
fmt.Println(0, MO, 1, TU) fmt.Println(0, MO, 1, TU)
} }
/* Output: /* Output:
The 3rd day is: Thursday The 3rd day is: Thursday
Sunday Sunday

View File

@@ -5,21 +5,22 @@ import "fmt"
/* basic data structure upon with we'll define methods */ /* basic data structure upon with we'll define methods */
type employee struct { type employee struct {
salary float32 salary float32
} }
/* a method which will add a specified percent to an /* a method which will add a specified percent to an
employees salary */ employees salary */
func (this *employee) giveRaise(pct float32) { func (this *employee) giveRaise(pct float32) {
this.salary += this.salary * pct this.salary += this.salary * pct
} }
func main() { func main() {
/* create an employee instance */ /* create an employee instance */
var e = new(employee) var e = new(employee)
e.salary = 100000; e.salary = 100000
/* call our method */ /* call our method */
e.giveRaise(0.04) e.giveRaise(0.04)
fmt.Printf("Employee now makes %f", e.salary) fmt.Printf("Employee now makes %f", e.salary)
} }
// Employee now makes 104000.000000 // Employee now makes 104000.000000

View File

@@ -3,7 +3,7 @@ package main
import "fmt" import "fmt"
type Base struct { type Base struct {
id string id string
} }
func (b *Base) Id() string { func (b *Base) Id() string {
@@ -16,13 +16,13 @@ func (b *Base) SetId(id string) {
type Person struct { type Person struct {
Base Base
FirstName string FirstName string
LastName string LastName string
} }
type Employee struct { type Employee struct {
Person Person
salary float32 salary float32
} }
func main() { func main() {
@@ -34,6 +34,7 @@ func main() {
e.SetId("007B") e.SetId("007B")
fmt.Printf("The new ID of our hero: %v\n", e.Id()) fmt.Printf("The new ID of our hero: %v\n", e.Id())
} }
/* Output: /* Output:
ID of our hero: 007 ID of our hero: 007
The new ID of our hero: 007B The new ID of our hero: 007B

View File

@@ -6,8 +6,8 @@ import (
) )
type Engine interface { type Engine interface {
Start() Start()
Stop() Stop()
} }
type Car struct { type Car struct {
@@ -17,16 +17,16 @@ type Car struct {
// define a behavior for Car // define a behavior for Car
func (car Car) numberOfWheels() int { func (car Car) numberOfWheels() int {
return car.wheelCount return car.wheelCount
} }
type Mercedes struct { type Mercedes struct {
Car //anonymous field Car Car //anonymous field Car
} }
// a behavior only available for the Mercedes // a behavior only available for the Mercedes
func (m *Mercedes) sayHiToMerkel() { func (m *Mercedes) sayHiToMerkel() {
fmt.Println("Hi Angela!") fmt.Println("Hi Angela!")
} }
func (c *Car) Start() { func (c *Car) Start() {
@@ -38,19 +38,20 @@ func (c *Car) Stop() {
} }
func (c *Car) GoToWorkIn() { func (c *Car) GoToWorkIn() {
// get in car // get in car
c.Start(); c.Start()
// drive to work // drive to work
c.Stop(); c.Stop()
// get out of car // get out of car
} }
func main() { func main() {
m := Mercedes{Car{4, nil}} m := Mercedes{Car{4, nil}}
fmt.Println("A Mercedes has this many wheels: ", m.numberOfWheels()) fmt.Println("A Mercedes has this many wheels: ", m.numberOfWheels())
m.GoToWorkIn() m.GoToWorkIn()
m.sayHiToMerkel() m.sayHiToMerkel()
} }
/* Output: /* Output:
A Mercedes has this many wheels: 4 A Mercedes has this many wheels: 4
Car is started Car is started

View File

@@ -17,7 +17,3 @@ func main() {
for _ = range lst.Iter() { for _ = range lst.Iter() {
} }
} }

View File

@@ -23,6 +23,7 @@ func main() {
v.Magic() v.Magic()
v.MoreMagic() v.MoreMagic()
} }
/* Output: /* Output:
voodoo magic voodoo magic
base magic base magic base magic base magic

View File

@@ -2,8 +2,8 @@
package main package main
import ( import (
"fmt"
"./stack/stack" "./stack/stack"
"fmt"
) )
func main() { func main() {
@@ -30,6 +30,7 @@ func main() {
fmt.Printf("Popped %d\n", p) fmt.Printf("Popped %d\n", p)
fmt.Printf("%v\n", st1) fmt.Printf("%v\n", st1)
} }
/* Output: /* Output:
[0:3] [0:3]
[0:3] [1:7] [0:3] [1:7]

View File

@@ -6,33 +6,34 @@ import (
) )
type Person struct { type Person struct {
firstName string firstName string
lastName string lastName string
} }
func upPerson (p Person) { func upPerson(p Person) {
p.firstName = strings.ToUpper(p.firstName) p.firstName = strings.ToUpper(p.firstName)
p.lastName = strings.ToUpper(p.lastName) p.lastName = strings.ToUpper(p.lastName)
} }
func main() { func main() {
// 1- struct as a value type: // 1- struct as a value type:
var pers1 Person var pers1 Person
pers1.firstName = "Chris" pers1.firstName = "Chris"
pers1.lastName = "Woodward" pers1.lastName = "Woodward"
upPerson(pers1) upPerson(pers1)
fmt.Printf("The name of the person is %s %s\n", pers1.firstName, pers1.lastName) fmt.Printf("The name of the person is %s %s\n", pers1.firstName, pers1.lastName)
// 2 - struct as a pointer: // 2 - struct as a pointer:
pers2 := new(Person) pers2 := new(Person)
pers2.firstName = "Chris" pers2.firstName = "Chris"
pers2.lastName = "Woodward" pers2.lastName = "Woodward"
upPerson(*pers2) upPerson(*pers2)
fmt.Printf("The name of the person is %s %s\n", pers2.firstName, pers2.lastName) fmt.Printf("The name of the person is %s %s\n", pers2.firstName, pers2.lastName)
// 3 - struct as a literal: // 3 - struct as a literal:
pers3 := &Person{"Chris","Woodward"} pers3 := &Person{"Chris", "Woodward"}
upPerson(*pers3) upPerson(*pers3)
fmt.Printf("The name of the person is %s %s\n", pers3.firstName, pers3.lastName) fmt.Printf("The name of the person is %s %s\n", pers3.firstName, pers3.lastName)
} }
/* Output: /* Output:
The name of the person is Chris Woodward The name of the person is Chris Woodward
The name of the person is Chris Woodward The name of the person is Chris Woodward

View File

@@ -21,7 +21,7 @@ func Abs(p *Point) float64 {
return math.Sqrt(float64(p.X*p.X + p.Y*p.Y)) return math.Sqrt(float64(p.X*p.X + p.Y*p.Y))
} }
func Scale(p *Point,s float64) (q Point) { func Scale(p *Point, s float64) (q Point) {
q.X = p.X * s q.X = p.X * s
q.Y = p.Y * s q.Y = p.Y * s
return return
@@ -31,19 +31,19 @@ func main() {
p1 := new(Point) p1 := new(Point)
p1.X = 3 p1.X = 3
p1.Y = 4 p1.Y = 4
fmt.Printf("The length of the vector p1 is: %f\n", Abs(p1) ) fmt.Printf("The length of the vector p1 is: %f\n", Abs(p1))
p2:= &Point{4, 5} p2 := &Point{4, 5}
fmt.Printf("The length of the vector p2 is: %f\n", Abs(p2) ) fmt.Printf("The length of the vector p2 is: %f\n", Abs(p2))
q := Scale(p1, 5) q := Scale(p1, 5)
fmt.Printf("The length of the vector q is: %f\n", Abs(&q) ) fmt.Printf("The length of the vector q is: %f\n", Abs(&q))
fmt.Printf("Point p1 scaled by 5 has the following coordinates: X %f - Y %f", q.X, q.Y) fmt.Printf("Point p1 scaled by 5 has the following coordinates: X %f - Y %f", q.X, q.Y)
} }
/* Output: /* Output:
The length of the vector p1 is: 5.000000 The length of the vector p1 is: 5.000000
The length of the vector p2 is: 6.403124 The length of the vector p2 is: 6.403124
The length of the vector q is: 25.000000 The length of the vector q is: 25.000000
Point p1 scaled by 5 has the following coordinates: X 15.000000 - Y 20.000000 Point p1 scaled by 5 has the following coordinates: X 15.000000 - Y 20.000000
*/ */

View File

@@ -39,13 +39,14 @@ func main() {
p1.Y = 4 p1.Y = 4
fmt.Printf("The length of the vector p1 is: %f\n", p1.Abs()) fmt.Printf("The length of the vector p1 is: %f\n", p1.Abs())
p2:= &Point{4, 5} p2 := &Point{4, 5}
fmt.Printf("The length of the vector p2 is: %f\n", p2.Abs() ) fmt.Printf("The length of the vector p2 is: %f\n", p2.Abs())
p1.Scale(5) p1.Scale(5)
fmt.Printf("The length of the vector p1 after scaling is: %f\n", p1.Abs() ) fmt.Printf("The length of the vector p1 after scaling is: %f\n", p1.Abs())
fmt.Printf("Point p1 after scaling has the following coordinates: X %f - Y %f", p1.X, p1.Y) fmt.Printf("Point p1 after scaling has the following coordinates: X %f - Y %f", p1.X, p1.Y)
} }
/* Output: /* Output:
The length of the vector p1 is: 5.000000 The length of the vector p1 is: 5.000000
The length of the vector p2 is: 6.403124 The length of the vector p2 is: 6.403124

View File

@@ -4,23 +4,24 @@ package main
import "fmt" import "fmt"
type Rectangle struct { type Rectangle struct {
length, width int length, width int
} }
func (r *Rectangle) Area() int { func (r *Rectangle) Area() int {
return r.length * r.width return r.length * r.width
} }
func (r *Rectangle) Perimeter() int { func (r *Rectangle) Perimeter() int {
return 2* (r.length + r.width) return 2 * (r.length + r.width)
} }
func main() { func main() {
r1 := Rectangle{4, 3} r1 := Rectangle{4, 3}
fmt.Println("Rectangle is: ", r1) fmt.Println("Rectangle is: ", r1)
fmt.Println("Rectangle area is: ", r1.Area()) fmt.Println("Rectangle area is: ", r1.Area())
fmt.Println("Rectangle perimeter is: ", r1.Perimeter()) fmt.Println("Rectangle perimeter is: ", r1.Perimeter())
} }
/* Output: /* Output:
Rectangle is: {4 3} Rectangle is: {4 3}
Rectangle area is: 12 Rectangle area is: 12

View File

@@ -2,16 +2,17 @@
package stack package stack
import "strconv" import "strconv"
const LIMIT = 10 const LIMIT = 10
type Stack struct { type Stack struct {
ix int // first free position, so data[ix] == 0 ix int // first free position, so data[ix] == 0
data [LIMIT]int data [LIMIT]int
} }
func (st *Stack) Push(n int) { func (st *Stack) Push(n int) {
if (st.ix + 1 > LIMIT) { if st.ix+1 > LIMIT {
return // stack is full! return // stack is full!
} }
st.data[st.ix] = n st.data[st.ix] = n
st.ix++ st.ix++
@@ -24,9 +25,8 @@ func (st *Stack) Pop() int {
func (st Stack) String() string { func (st Stack) String() string {
str := "" str := ""
for ix:=0; ix<st.ix; ix++ { for ix := 0; ix < st.ix; ix++ {
str += "[" + strconv.Itoa(ix) + ":" + strconv.Itoa(st.data[ix]) + "] " str += "[" + strconv.Itoa(ix) + ":" + strconv.Itoa(st.data[ix]) + "] "
} }
return str return str
} }

View File

@@ -6,6 +6,7 @@ import (
) )
const LIMIT = 4 const LIMIT = 4
type Stack [LIMIT]int type Stack [LIMIT]int
func main() { func main() {
@@ -46,8 +47,8 @@ func (st *Stack) Push(n int) {
// take value from first position which contains !=0, starting from top // take value from first position which contains !=0, starting from top
func (st *Stack) Pop() int { func (st *Stack) Pop() int {
v := 0 v := 0
for ix:= len(st)-1; ix>=0; ix-- { for ix := len(st) - 1; ix >= 0; ix-- {
if v=st[ix]; v!=0 { if v = st[ix]; v != 0 {
st[ix] = 0 st[ix] = 0
return v return v
} }

View File

@@ -7,9 +7,10 @@ import (
) )
const LIMIT = 4 const LIMIT = 4
type Stack struct { type Stack struct {
ix int // first free position, so data[ix] == 0 ix int // first free position, so data[ix] == 0
data [LIMIT]int data [LIMIT]int
} }
func main() { func main() {
@@ -38,8 +39,8 @@ func main() {
} }
func (st *Stack) Push(n int) { func (st *Stack) Push(n int) {
if (st.ix + 1 > LIMIT) { if st.ix+1 > LIMIT {
return // stack is full! return // stack is full!
} }
st.data[st.ix] = n st.data[st.ix] = n
st.ix++ st.ix++
@@ -52,7 +53,7 @@ func (st *Stack) Pop() int {
func (st Stack) String() string { func (st Stack) String() string {
str := "" str := ""
for ix:=0; ix<st.ix; ix++ { for ix := 0; ix < st.ix; ix++ {
str += "[" + strconv.Itoa(ix) + ":" + strconv.Itoa(st.data[ix]) + "] " str += "[" + strconv.Itoa(ix) + ":" + strconv.Itoa(st.data[ix]) + "] "
} }
return str return str

View File

@@ -15,11 +15,11 @@ const (
CST TZ = -6 * HOUR CST TZ = -6 * HOUR
) )
var timeZones = map[TZ]string { UTC:"Universal Greenwich time", var timeZones = map[TZ]string{UTC: "Universal Greenwich time",
EST:"Eastern Standard time", EST: "Eastern Standard time",
CST:"Central Standard time" } CST: "Central Standard time"}
func (tz TZ) String() string { // Method on TZ (not ptr) func (tz TZ) String() string { // Method on TZ (not ptr)
for name, zone := range timeZones { for name, zone := range timeZones {
if tz == name { if tz == name {
return zone return zone
@@ -29,10 +29,11 @@ func (tz TZ) String() string { // Method on TZ (not ptr)
} }
func main() { func main() {
fmt.Println(EST) // Print* knows about method String() of type TZ fmt.Println(EST) // Print* knows about method String() of type TZ
fmt.Println(0 * HOUR) fmt.Println(0 * HOUR)
fmt.Println(-6 * HOUR) fmt.Println(-6 * HOUR)
} }
/* Output: /* Output:
Eastern Standard time Eastern Standard time
Universal Greenwich time Universal Greenwich time

View File

@@ -3,17 +3,18 @@ package main
import "fmt" import "fmt"
type T struct { type T struct {
a int a int
b float32 b float32
c string c string
} }
func main() { func main() {
t := &T{ 7, -2.35, "abc\tdef" } t := &T{7, -2.35, "abc\tdef"}
fmt.Printf("%v\n", t) fmt.Printf("%v\n", t)
} }
func (t *T) String() string { func (t *T) String() string {
return fmt.Sprintf("%d / %f / %q", t.a, t.b, t.c) return fmt.Sprintf("%d / %f / %q", t.a, t.b, t.c)
} }
// Output: 7 / -2.350000 / "abc\tdef" // Output: 7 / -2.350000 / "abc\tdef"

View File

@@ -16,17 +16,17 @@ type Address struct {
} }
type VCard struct { type VCard struct {
FirstName string FirstName string
LastName string LastName string
NickName string NickName string
BirtDate time.Time BirtDate time.Time
Photo string Photo string
Addresses map[string]*Address Addresses map[string]*Address
} }
func main() { func main() {
addr1 := &Address{"Elfenstraat", 12, "", "", "2600", "Mechelen", "België" } addr1 := &Address{"Elfenstraat", 12, "", "", "2600", "Mechelen", "België"}
addr2 := &Address{"Heideland", 28, "", "", "2640", "Mortsel", "België" } addr2 := &Address{"Heideland", 28, "", "", "2640", "Mortsel", "België"}
addrs := make(map[string]*Address) addrs := make(map[string]*Address)
addrs["youth"] = addr1 addrs["youth"] = addr1
addrs["now"] = addr2 addrs["now"] = addr2
@@ -36,6 +36,7 @@ func main() {
fmt.Printf("Here is the full VCard: %v\n", vcard) fmt.Printf("Here is the full VCard: %v\n", vcard)
fmt.Printf("My Addresses are:\n %v\n %v", addr1, addr2) fmt.Printf("My Addresses are:\n %v\n %v", addr1, addr2)
} }
/* Output: /* Output:
Here is the full VCard: &{Ivo Balbaert Sun Jan 17 15:04:05 +0000 1956 MyDocuments/MyPhotos/photo1.jpg map[now:0x126d57c0 youth:0x126d5500]} Here is the full VCard: &{Ivo Balbaert Sun Jan 17 15:04:05 +0000 1956 MyDocuments/MyPhotos/photo1.jpg map[now:0x126d57c0 youth:0x126d5500]}
My Addresses are: My Addresses are: