From 416e29d95affef58df80185e19d10378952630fe Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Sat, 11 Feb 2017 12:34:46 +0800 Subject: [PATCH] fix: coding style and file format for all example. --- eBook/examples/chapter_10/embed_func1.go | 87 ++++---- eBook/examples/chapter_10/embed_func2.go | 76 +++---- eBook/examples/chapter_10/embedd_struct.go | 36 ++-- eBook/examples/chapter_10/main.go | 33 +-- eBook/examples/chapter_10/method1.go | 58 +++--- eBook/examples/chapter_10/method2.go | 32 +-- eBook/examples/chapter_10/method3.go | 48 ++--- eBook/examples/chapter_10/method4.go | 56 +++--- eBook/examples/chapter_10/method_on_time.go | 51 ++--- eBook/examples/chapter_10/method_string.go | 52 +++-- eBook/examples/chapter_10/methodset1.go | 45 +++-- eBook/examples/chapter_10/mult_inheritance.go | 69 +++---- eBook/examples/chapter_10/new_make.go | 54 ++--- eBook/examples/chapter_10/person.go | 83 ++++---- eBook/examples/chapter_10/person2.go | 31 ++- eBook/examples/chapter_10/pointer_value.go | 57 +++--- .../examples/chapter_10/struct_conversions.go | 49 ++--- .../chapter_10/struct_pack/structPack.go | 12 +- eBook/examples/chapter_10/struct_tag.go | 61 +++--- .../chapter_10/structs_anonymous_fields.go | 68 +++---- eBook/examples/chapter_10/structs_fields.go | 46 ++--- eBook/examples/chapter_10/use_person2.go | 28 +-- eBook/examples/chapter_11/cars.go | 189 +++++++++--------- eBook/examples/chapter_11/duck_dance.go | 64 +++--- eBook/examples/chapter_11/empty_interface.go | 76 +++---- eBook/examples/chapter_11/emptyint_switch.go | 1 + eBook/examples/chapter_11/interfaces.go | 61 +++--- eBook/examples/chapter_11/interfaces_poly.go | 88 ++++---- eBook/examples/chapter_11/methodset2.go | 97 ++++----- .../chapter_11/multi_interfaces_poly.go | 131 ++++++------ eBook/examples/chapter_11/node_structures.go | 62 +++--- eBook/examples/chapter_11/print.go | 93 +++++---- eBook/examples/chapter_11/reflect1.go | 65 +++--- eBook/examples/chapter_11/reflect2.go | 67 ++++--- eBook/examples/chapter_11/reflect_struct.go | 95 ++++----- eBook/examples/chapter_11/reflect_struct2.go | 63 +++--- eBook/examples/chapter_11/sort/sort.go | 118 +++++------ eBook/examples/chapter_11/sortmain.go | 163 ++++++++------- eBook/examples/chapter_11/static.go | 46 ++--- .../tideland-cgl.googlecode.com/hg/cgl.go | 8 +- .../tideland-cgl.googlecode.com/hg/cglmon.go | 4 +- eBook/examples/chapter_11/type_interfaces.go | 124 ++++++------ eBook/examples/chapter_12/cat.go | 71 ++++--- eBook/examples/chapter_12/cat2.go | 82 ++++---- eBook/examples/chapter_12/echo.go | 58 +++--- eBook/examples/chapter_12/filecopy.go | 58 +++--- eBook/examples/chapter_12/fileinput.go | 68 +++---- eBook/examples/chapter_12/fileoutput.go | 56 +++--- eBook/examples/chapter_12/filewrite.go | 20 +- eBook/examples/chapter_12/gob1.go | 83 ++++---- eBook/examples/chapter_12/gob2.go | 77 ++++--- eBook/examples/chapter_12/gzipped.go | 70 +++---- eBook/examples/chapter_12/hash_sha1.go | 63 +++--- eBook/examples/chapter_12/io_interfaces.go | 36 ++-- eBook/examples/chapter_12/json.go | 80 ++++---- eBook/examples/chapter_12/json_xml_case.go | 109 +++++----- eBook/examples/chapter_12/os_args.go | 32 +-- eBook/examples/chapter_12/read_file2.go | 77 +++---- eBook/examples/chapter_12/read_files.go | 58 +++--- eBook/examples/chapter_12/read_write_file1.go | 42 ++-- eBook/examples/chapter_12/readinput1.go | 48 ++--- eBook/examples/chapter_12/readinput2.go | 44 ++-- eBook/examples/chapter_12/switch_input.go | 92 +++++---- eBook/examples/chapter_12/xml.go | 99 ++++----- eBook/examples/chapter_13/errors.go | 29 +-- eBook/examples/chapter_13/even/even/even.go | 20 +- .../chapter_13/even/even/oddeven_test.go | 54 ++--- .../chapter_13/even/even_main/even_main.go | 26 +-- eBook/examples/chapter_13/exec.go | 122 +++++------ eBook/examples/chapter_13/panic.go | 18 +- eBook/examples/chapter_13/panic_package.go | 79 ++++---- eBook/examples/chapter_13/panic_recover.go | 64 +++--- eBook/examples/chapter_13/parse/parse.go | 102 +++++----- .../examples/chapter_14/benchmark_channels.go | 70 +++---- eBook/examples/chapter_14/chaining.go | 8 +- eBook/examples/chapter_14/channel_block.go | 31 ++- eBook/examples/chapter_14/channel_block2.go | 50 ++--- eBook/examples/chapter_14/channel_idiom2.go | 58 +++--- eBook/examples/chapter_14/conc_access.go | 109 +++++----- .../chapter_14/general_lazy_evalution1.go | 115 +++++------ eBook/examples/chapter_14/goroutine1.go | 58 +++--- eBook/examples/chapter_14/goroutine2.go | 67 ++++--- eBook/examples/chapter_14/goroutine3.go | 59 +++--- eBook/examples/chapter_14/goroutine_select.go | 80 ++++---- .../examples/chapter_14/goroutine_select2.go | 96 +++++---- eBook/examples/chapter_14/lazy_evaluation.go | 60 +++--- eBook/examples/chapter_14/max_tasks.go | 63 +++--- eBook/examples/chapter_14/multiplex_server.go | 106 +++++----- .../examples/chapter_14/multiplex_server2.go | 116 +++++------ eBook/examples/chapter_14/sieve1.go | 74 +++---- eBook/examples/chapter_14/sieve2.go | 106 +++++----- eBook/examples/chapter_14/timer_goroutine.go | 85 ++++---- .../chapter_16/closures_goroutines.go | 95 ++++----- .../examples/chapter_16/pointer_interface.go | 61 +++--- eBook/examples/chapter_19/goto_v1/main.go | 2 +- eBook/examples/chapter_19/goto_v1/store.go | 4 +- eBook/examples/chapter_19/goto_v2/main.go | 1 - eBook/examples/chapter_19/goto_v2/store.go | 8 +- eBook/examples/chapter_19/goto_v3/store.go | 20 +- eBook/examples/chapter_19/goto_v4/store.go | 12 +- eBook/examples/chapter_19/goto_v5/main.go | 2 +- eBook/examples/chapter_19/goto_v5/store.go | 10 +- eBook/examples/chapter_2/hello_world1.go | 13 +- eBook/examples/chapter_2/version.go | 25 +-- .../helloapp/hello/helloworld2_version1.go | 28 +-- .../helloapp/hello/helloworld2_version2.go | 56 +++--- .../helloapp/hello/helloworld2_version3.go | 92 ++++----- .../helloapp/hello/helloworld2_version4.go | 145 +++++++------- eBook/examples/chapter_20/helloworld.go | 31 ++- eBook/examples/chapter_3/CandGo/c1.go | 26 +-- eBook/examples/chapter_3/CandGo/c2.go | 26 +-- eBook/examples/chapter_4/alias.go | 14 +- eBook/examples/chapter_4/casting.go | 38 ++-- eBook/examples/chapter_4/char.go | 45 +++-- eBook/examples/chapter_4/count_substring.go | 34 ++-- .../chapter_4/function_calls_function.go | 32 +-- eBook/examples/chapter_4/global_scope.go | 30 +-- eBook/examples/chapter_4/gotemplate.go | 60 +++--- eBook/examples/chapter_4/hello_world.go | 14 +- eBook/examples/chapter_4/hello_world2.go | 14 +- eBook/examples/chapter_4/index_in_string.go | 42 ++-- eBook/examples/chapter_4/local_scope.go | 26 +-- eBook/examples/chapter_4/pointer.go | 24 +-- eBook/examples/chapter_4/presuffix.go | 29 +-- eBook/examples/chapter_4/random.go | 57 +++--- eBook/examples/chapter_4/repeat_string.go | 28 +-- eBook/examples/chapter_4/string_conversion.go | 40 ++-- eBook/examples/chapter_4/string_pointer.go | 26 +-- eBook/examples/chapter_4/strings_splitjoin.go | 67 ++++--- eBook/examples/chapter_4/testcrash.go | 23 ++- eBook/examples/chapter_4/time.go | 54 ++--- eBook/examples/chapter_4/toupper_lower.go | 36 ++-- eBook/examples/chapter_4/type.go | 22 +- eBook/examples/chapter_4/type_mixing.go | 18 +- eBook/examples/chapter_4/use_init.go | 24 +-- eBook/examples/chapter_4/user_init.go | 21 +- eBook/examples/chapter_5/booleans.go | 24 +-- eBook/examples/chapter_5/for1.go | 18 +- eBook/examples/chapter_5/for2.go | 24 +-- eBook/examples/chapter_5/for3.go | 30 +-- eBook/examples/chapter_5/for4.go | 26 +-- eBook/examples/chapter_5/for5.go | 22 +- eBook/examples/chapter_5/for6.go | 34 ++-- eBook/examples/chapter_5/for_string.go | 115 +++++------ eBook/examples/chapter_5/goto.go | 24 +-- eBook/examples/chapter_5/goto2.go | 26 +-- eBook/examples/chapter_5/ifelse.go | 44 ++-- eBook/examples/chapter_5/range_string.go | 161 +++++++-------- .../examples/chapter_5/string_conversion2.go | 50 ++--- eBook/examples/chapter_5/switch1.go | 32 +-- eBook/examples/chapter_5/switch2.go | 32 +-- eBook/examples/chapter_6/blank_identifier.go | 28 +-- eBook/examples/chapter_6/defer.go | 34 ++-- eBook/examples/chapter_6/defer_dbconn.go | 74 ++++--- eBook/examples/chapter_6/defer_logvalues.go | 39 ++-- eBook/examples/chapter_6/defer_tracing.go | 44 ++-- eBook/examples/chapter_6/defer_tracing2.go | 50 ++--- eBook/examples/chapter_6/fibonacci.go | 113 +++++------ .../chapter_6/fibonacci_memoization.go | 86 ++++---- eBook/examples/chapter_6/filter_factory.go | 108 +++++----- eBook/examples/chapter_6/function_closure.go | 36 ++-- eBook/examples/chapter_6/function_filter.go | 98 ++++----- eBook/examples/chapter_6/function_literal.go | 31 +-- .../examples/chapter_6/function_parameter.go | 40 ++-- eBook/examples/chapter_6/function_return.go | 56 +++--- eBook/examples/chapter_6/greeting.go | 22 +- eBook/examples/chapter_6/minmax.go | 40 ++-- eBook/examples/chapter_6/multiple_return.go | 56 +++--- eBook/examples/chapter_6/mut_recurs.go | 60 +++--- eBook/examples/chapter_6/return_defer.go | 37 ++-- eBook/examples/chapter_6/side_effect.go | 36 ++-- eBook/examples/chapter_6/simple_function.go | 30 +-- eBook/examples/chapter_6/varnumpar.go | 57 +++--- eBook/examples/chapter_7/array_literals.go | 48 ++--- eBook/examples/chapter_7/array_slices.go | 66 +++--- eBook/examples/chapter_7/array_sum.go | 35 ++-- eBook/examples/chapter_7/copy_append_slice.go | 32 +-- eBook/examples/chapter_7/for_arrays.go | 32 +-- eBook/examples/chapter_7/for_string.go | 23 ++- eBook/examples/chapter_7/make_slice.go | 36 ++-- eBook/examples/chapter_7/multidim_array.go | 72 +++---- eBook/examples/chapter_7/pointer_array.go | 24 +-- eBook/examples/chapter_7/pointer_array2.go | 22 +- eBook/examples/chapter_7/reslicing.go | 36 ++-- eBook/examples/chapter_7/slices_forrange.go | 45 +++-- eBook/examples/chapter_7/slices_forrange2.go | 63 +++--- eBook/examples/chapter_8/invert_map.go | 58 +++--- eBook/examples/chapter_8/make_maps.go | 1 + eBook/examples/chapter_8/map_func.go | 28 +-- eBook/examples/chapter_8/map_testelement.go | 66 +++--- eBook/examples/chapter_8/maps_forrange.go | 30 +-- eBook/examples/chapter_8/slice_maps.go | 55 ++--- eBook/examples/chapter_8/sort_map.go | 86 ++++---- eBook/examples/chapter_9/big.go | 61 +++--- .../examples/chapter_9/book/book_main/main.go | 28 +-- eBook/examples/chapter_9/book/pack1/pack1.go | 16 +- eBook/examples/chapter_9/book/package_test.go | 14 +- eBook/examples/chapter_9/doc_example/sort.go | 120 +++++------ .../chapter_9/doc_example/sortmain.go | 163 ++++++++------- eBook/examples/chapter_9/pattern.go | 71 +++---- eBook/examples/chapter_9/reboot.go | 42 ++-- eBook/examples/chapter_9/test.go | 6 +- eBook/examples/chapter_9/uppercase/uc/uc.go | 16 +- .../chapter_9/uppercase/uc/uc_test.go | 46 ++--- .../chapter_9/uppercase/uc_main/ucmain.go | 24 +-- eBook/examples/chapter_9/use_urlshortener.go | 110 +++++----- 206 files changed, 5531 insertions(+), 5451 deletions(-) diff --git a/eBook/examples/chapter_10/embed_func1.go b/eBook/examples/chapter_10/embed_func1.go index ed92f27..a849298 100644 --- a/eBook/examples/chapter_10/embed_func1.go +++ b/eBook/examples/chapter_10/embed_func1.go @@ -1,43 +1,44 @@ -package main - -import ( - "fmt" -) - -type Log struct { - msg string -} - -type Customer struct { - Name string - log *Log -} - -func main() { - // c := new(Customer) - // c.Name = "Barak Obama" - // c.log = new(Log) - // c.log.msg = "1 - Yes we can!" - // shorter: - c := &Customer{"Barak Obama", &Log{"1 - Yes we can!"}} - // fmt.Println(c) // &{Barak Obama 1 - Yes we can!} - c.Log().Add("2 - After me the world will be a better place!") - //fmt.Println(c.log) - fmt.Println(c.Log()) -} - -func (l *Log) Add(s string) { - l.msg += "\n" + s -} - -func (l *Log) String() string { - return l.msg -} - -func (c *Customer) Log() *Log { - return c.log -} -/* Output: -1 - Yes we can! -2 - After me the world will be a better place! -*/ \ No newline at end of file +package main + +import ( + "fmt" +) + +type Log struct { + msg string +} + +type Customer struct { + Name string + log *Log +} + +func main() { + // c := new(Customer) + // c.Name = "Barak Obama" + // c.log = new(Log) + // c.log.msg = "1 - Yes we can!" + // shorter: + c := &Customer{"Barak Obama", &Log{"1 - Yes we can!"}} + // fmt.Println(c) // &{Barak Obama 1 - Yes we can!} + c.Log().Add("2 - After me the world will be a better place!") + //fmt.Println(c.log) + fmt.Println(c.Log()) +} + +func (l *Log) Add(s string) { + l.msg += "\n" + s +} + +func (l *Log) String() string { + return l.msg +} + +func (c *Customer) Log() *Log { + return c.log +} + +/* Output: +1 - Yes we can! +2 - After me the world will be a better place! +*/ diff --git a/eBook/examples/chapter_10/embed_func2.go b/eBook/examples/chapter_10/embed_func2.go index f26b7e4..313930e 100644 --- a/eBook/examples/chapter_10/embed_func2.go +++ b/eBook/examples/chapter_10/embed_func2.go @@ -1,38 +1,38 @@ -package main - -import ( - "fmt" -) - -type Log struct { - msg string -} - -type Customer struct { - Name string - Log -} - -func main() { - c := &Customer{"Barak Obama", Log{"1 - Yes we can!"}} - c.Add("2 - After me the world will be a better place!") - fmt.Println(c) -} - -func (l *Log) Add(s string) { - l.msg += "\n" + s -} - -func (c *Customer) String() string { - return c.Name + "\nLog:" + fmt.Sprintln(c.Log) -} - -func (l *Log) String() string { - return l.msg -} - -/* Output: -Barak Obama -Log:{1 - Yes we can! -2 - After me the world will be a better place!} -*/ \ No newline at end of file +package main + +import ( + "fmt" +) + +type Log struct { + msg string +} + +type Customer struct { + Name string + Log +} + +func main() { + c := &Customer{"Barak Obama", Log{"1 - Yes we can!"}} + c.Add("2 - After me the world will be a better place!") + fmt.Println(c) +} + +func (l *Log) Add(s string) { + l.msg += "\n" + s +} + +func (c *Customer) String() string { + return c.Name + "\nLog:" + fmt.Sprintln(c.Log) +} + +func (l *Log) String() string { + return l.msg +} + +/* Output: +Barak Obama +Log:{1 - Yes we can! +2 - After me the world will be a better place!} +*/ diff --git a/eBook/examples/chapter_10/embedd_struct.go b/eBook/examples/chapter_10/embedd_struct.go index bb24088..3586131 100644 --- a/eBook/examples/chapter_10/embedd_struct.go +++ b/eBook/examples/chapter_10/embedd_struct.go @@ -1,18 +1,18 @@ -package main - -import "fmt" - -type A struct { - ax, ay int -} - -type B struct { - A - bx, by float32 -} - -func main() { - b := B{A{1, 2}, 3.0, 4.0} - fmt.Println(b.ax, b.ay, b.bx, b.by) - fmt.Println(b.A) -} +package main + +import "fmt" + +type A struct { + ax, ay int +} + +type B struct { + A + bx, by float32 +} + +func main() { + b := B{A{1, 2}, 3.0, 4.0} + fmt.Println(b.ax, b.ay, b.bx, b.by) + fmt.Println(b.A) +} diff --git a/eBook/examples/chapter_10/main.go b/eBook/examples/chapter_10/main.go index 8fecd16..8387f6f 100644 --- a/eBook/examples/chapter_10/main.go +++ b/eBook/examples/chapter_10/main.go @@ -1,16 +1,17 @@ -package main - -import ( - "fmt" - "./struct_pack/structPack" -) - -func main() { - struct1 := new(structPack.ExpStruct) - struct1.Mi1 = 10 - struct1.Mf1 = 16. - fmt.Printf("Mi1 = %d\n", struct1.Mi1) - fmt.Printf("Mf1 = %f\n", struct1.Mf1) -} -// Mi1 = 10 -// Mf1 = 16.000000 \ No newline at end of file +package main + +import ( + "./struct_pack/structPack" + "fmt" +) + +func main() { + struct1 := new(structPack.ExpStruct) + struct1.Mi1 = 10 + struct1.Mf1 = 16. + fmt.Printf("Mi1 = %d\n", struct1.Mi1) + fmt.Printf("Mf1 = %f\n", struct1.Mf1) +} + +// Mi1 = 10 +// Mf1 = 16.000000 diff --git a/eBook/examples/chapter_10/method1.go b/eBook/examples/chapter_10/method1.go index 35280f0..2aea0d8 100644 --- a/eBook/examples/chapter_10/method1.go +++ b/eBook/examples/chapter_10/method1.go @@ -1,29 +1,29 @@ -package main - -import "fmt" - -type TwoInts struct { - a int - b int -} - -func main() { - two1 := new(TwoInts) - two1.a = 12 - two1.b = 10 - - fmt.Printf("The sum is: %d\n", two1.AddThem()) - fmt.Printf("Add them to the param: %d\n", two1.AddToParam(20)) - - // literal: - two2 := TwoInts{3, 4} - fmt.Printf("The sum is: %d\n", two2.AddThem()) -} - -func (tn *TwoInts) AddThem() int { - return tn.a + tn.b -} - -func (tn *TwoInts) AddToParam(param int) int { - return tn.a + tn.b + param -} +package main + +import "fmt" + +type TwoInts struct { + a int + b int +} + +func main() { + two1 := new(TwoInts) + two1.a = 12 + two1.b = 10 + + fmt.Printf("The sum is: %d\n", two1.AddThem()) + fmt.Printf("Add them to the param: %d\n", two1.AddToParam(20)) + + // literal: + two2 := TwoInts{3, 4} + fmt.Printf("The sum is: %d\n", two2.AddThem()) +} + +func (tn *TwoInts) AddThem() int { + return tn.a + tn.b +} + +func (tn *TwoInts) AddToParam(param int) int { + return tn.a + tn.b + param +} diff --git a/eBook/examples/chapter_10/method2.go b/eBook/examples/chapter_10/method2.go index f6fc530..95c4ceb 100644 --- a/eBook/examples/chapter_10/method2.go +++ b/eBook/examples/chapter_10/method2.go @@ -1,16 +1,16 @@ -package main - -import "fmt" - -type IntVector []int - -func (v IntVector) Sum() (s int) { - for _, x := range v { - s += x - } - return -} - -func main() { - fmt.Println(IntVector{1, 2, 3}.Sum()) // Output: 6 -} +package main + +import "fmt" + +type IntVector []int + +func (v IntVector) Sum() (s int) { + for _, x := range v { + s += x + } + return +} + +func main() { + fmt.Println(IntVector{1, 2, 3}.Sum()) // Output: 6 +} diff --git a/eBook/examples/chapter_10/method3.go b/eBook/examples/chapter_10/method3.go index a5b11d6..6ca8ebc 100644 --- a/eBook/examples/chapter_10/method3.go +++ b/eBook/examples/chapter_10/method3.go @@ -1,24 +1,24 @@ -package main - -import ( - "fmt" - "math" -) - -type Point struct { - x, y float64 -} - -func (p *Point) Abs() float64 { - return math.Sqrt(p.x*p.x + p.y*p.y) -} - -type NamedPoint struct { - Point - name string -} - -func main() { - n := &NamedPoint{Point{3, 4}, "Pythagoras"} - fmt.Println(n.Abs()) // prints 5 -} +package main + +import ( + "fmt" + "math" +) + +type Point struct { + x, y float64 +} + +func (p *Point) Abs() float64 { + return math.Sqrt(p.x*p.x + p.y*p.y) +} + +type NamedPoint struct { + Point + name string +} + +func main() { + n := &NamedPoint{Point{3, 4}, "Pythagoras"} + fmt.Println(n.Abs()) // prints 5 +} diff --git a/eBook/examples/chapter_10/method4.go b/eBook/examples/chapter_10/method4.go index 7d8b55a..de779d9 100644 --- a/eBook/examples/chapter_10/method4.go +++ b/eBook/examples/chapter_10/method4.go @@ -1,28 +1,28 @@ -package main - -import ( - "fmt" - "math" -) - -type Point struct { - x, y float64 -} - -func (p *Point) Abs() float64 { - return math.Sqrt(p.x*p.x + p.y*p.y) -} - -type NamedPoint struct { - Point - name string -} - -func (n *NamedPoint) Abs() float64 { - return n.Point.Abs() * 100. -} - -func main() { - n := &NamedPoint{Point{3, 4}, "Pythagoras"} - fmt.Println(n.Abs()) // prints 500 -} +package main + +import ( + "fmt" + "math" +) + +type Point struct { + x, y float64 +} + +func (p *Point) Abs() float64 { + return math.Sqrt(p.x*p.x + p.y*p.y) +} + +type NamedPoint struct { + Point + name string +} + +func (n *NamedPoint) Abs() float64 { + return n.Point.Abs() * 100. +} + +func main() { + n := &NamedPoint{Point{3, 4}, "Pythagoras"} + fmt.Println(n.Abs()) // prints 500 +} diff --git a/eBook/examples/chapter_10/method_on_time.go b/eBook/examples/chapter_10/method_on_time.go index ee422ae..c105846 100644 --- a/eBook/examples/chapter_10/method_on_time.go +++ b/eBook/examples/chapter_10/method_on_time.go @@ -1,25 +1,26 @@ -// method_on_time.go -package main - -import ( - "fmt" - "time" -) - -type myTime struct { - time.Time //anonymous field -} - -func (t myTime) first3Chars() string { - return t.Time.String()[0:3] -} - -func main() { - m := myTime{time.Now()} - fmt.Println("Full time now:", m.String()) //calling existing String method on anonymous Time field - fmt.Println("First 3 chars:", m.first3Chars()) //calling myTime.first3Chars -} -/* Output: -Full time now: Mon Oct 24 15:34:54 Romance Daylight Time 2011 -First 3 chars: Mon -*/ \ No newline at end of file +// method_on_time.go +package main + +import ( + "fmt" + "time" +) + +type myTime struct { + time.Time //anonymous field +} + +func (t myTime) first3Chars() string { + return t.Time.String()[0:3] +} + +func main() { + m := myTime{time.Now()} + fmt.Println("Full time now:", m.String()) //calling existing String method on anonymous Time field + fmt.Println("First 3 chars:", m.first3Chars()) //calling myTime.first3Chars +} + +/* Output: +Full time now: Mon Oct 24 15:34:54 Romance Daylight Time 2011 +First 3 chars: Mon +*/ diff --git a/eBook/examples/chapter_10/method_string.go b/eBook/examples/chapter_10/method_string.go index 0213139..b242212 100644 --- a/eBook/examples/chapter_10/method_string.go +++ b/eBook/examples/chapter_10/method_string.go @@ -1,27 +1,25 @@ -package main - -import ( - "fmt" - "strconv" -) - -type TwoInts struct { - a int - b int -} - -func main() { - two1 := new(TwoInts) - two1.a = 12 - two1.b = 10 - fmt.Printf("two1 is: %v\n", two1) - fmt.Println("two1 is:", two1) - fmt.Printf("two1 is: %T\n", two1) - fmt.Printf("two1 is: %#v\n", two1) -} - -func (tn *TwoInts) String() string { - return "(" + strconv.Itoa(tn.a) + " / " + strconv.Itoa(tn.b) + ")" -} - - +package main + +import ( + "fmt" + "strconv" +) + +type TwoInts struct { + a int + b int +} + +func main() { + two1 := new(TwoInts) + two1.a = 12 + two1.b = 10 + fmt.Printf("two1 is: %v\n", two1) + fmt.Println("two1 is:", two1) + fmt.Printf("two1 is: %T\n", two1) + fmt.Printf("two1 is: %#v\n", two1) +} + +func (tn *TwoInts) String() string { + return "(" + strconv.Itoa(tn.a) + " / " + strconv.Itoa(tn.b) + ")" +} diff --git a/eBook/examples/chapter_10/methodset1.go b/eBook/examples/chapter_10/methodset1.go index c8d8c6d..7a4e758 100644 --- a/eBook/examples/chapter_10/methodset1.go +++ b/eBook/examples/chapter_10/methodset1.go @@ -1,22 +1,23 @@ -// methodset1.go -package main - -import ( - "fmt" -) - -type List []int -func (l List) Len() int { return len(l) } -func (l *List) Append(val int) { *l = append(*l, val) } - -func main() { - // A bare value - var lst List - lst.Append(1) - fmt.Printf("%v (len: %d)\n", lst, lst.Len()) // [1] (len: 1) - - // A pointer value - plst := new(List) - plst.Append(2) - fmt.Printf("%v (len: %d)\n", plst, lst.Len()) // &[2] (len: 1) -} +// methodset1.go +package main + +import ( + "fmt" +) + +type List []int + +func (l List) Len() int { return len(l) } +func (l *List) Append(val int) { *l = append(*l, val) } + +func main() { + // A bare value + var lst List + lst.Append(1) + fmt.Printf("%v (len: %d)\n", lst, lst.Len()) // [1] (len: 1) + + // A pointer value + plst := new(List) + plst.Append(2) + fmt.Printf("%v (len: %d)\n", plst, lst.Len()) // &[2] (len: 1) +} diff --git a/eBook/examples/chapter_10/mult_inheritance.go b/eBook/examples/chapter_10/mult_inheritance.go index 79d1ece..c1d52f3 100644 --- a/eBook/examples/chapter_10/mult_inheritance.go +++ b/eBook/examples/chapter_10/mult_inheritance.go @@ -1,34 +1,35 @@ -// mult_inheritance.go -package main - -import "fmt" - -type Camera struct { } - -func (c *Camera) TakeAPicture() string { - return "Click" -} - -type Phone struct { } - -func (p *Phone ) Call() string { - return "Ring Ring" -} - -// multiple inheritance -type CameraPhone struct { - Camera - Phone -} - -func main() { - cp := new(CameraPhone) - fmt.Println("Our new CameraPhone exhibits multiple behaviors ...") - fmt.Println("It exhibits behavior of a Camera: ", cp.TakeAPicture()) - fmt.Println("It works like a Phone too: ", cp.Call()) -} -/* Output: -Our new CameraPhone exhibits multiple behaviors ... -It exhibits behavior of a Camera: Click -It works like a Phone too: Ring Ring -*/ \ No newline at end of file +// mult_inheritance.go +package main + +import "fmt" + +type Camera struct{} + +func (c *Camera) TakeAPicture() string { + return "Click" +} + +type Phone struct{} + +func (p *Phone) Call() string { + return "Ring Ring" +} + +// multiple inheritance +type CameraPhone struct { + Camera + Phone +} + +func main() { + cp := new(CameraPhone) + fmt.Println("Our new CameraPhone exhibits multiple behaviors ...") + fmt.Println("It exhibits behavior of a Camera: ", cp.TakeAPicture()) + fmt.Println("It works like a Phone too: ", cp.Call()) +} + +/* Output: +Our new CameraPhone exhibits multiple behaviors ... +It exhibits behavior of a Camera: Click +It works like a Phone too: Ring Ring +*/ diff --git a/eBook/examples/chapter_10/new_make.go b/eBook/examples/chapter_10/new_make.go index 27ed57b..200875b 100644 --- a/eBook/examples/chapter_10/new_make.go +++ b/eBook/examples/chapter_10/new_make.go @@ -1,27 +1,27 @@ -// annoy1.go -package main - -type Foo map[string]string -type Bar struct { - thingOne string - thingTwo int -} - -func main() { - // OK: - y := new(Bar) - (*y).thingOne = "hello" - (*y).thingTwo = 1 - // not OK: - z := make(Bar) // compile error: cannot make type Bar - z.thingOne = "hello" - z.thingTwo = 1 - // OK: - x := make(Foo) - x["x"] = "goodbye" - x["y"] = "world" - // not OK: - u := new(Foo) - (*u)["x"] = "goodbye" // !! panic !!: runtime error: assignment to entry in nil map - (*u)["y"] = "world" -} +// annoy1.go +package main + +type Foo map[string]string +type Bar struct { + thingOne string + thingTwo int +} + +func main() { + // OK: + y := new(Bar) + (*y).thingOne = "hello" + (*y).thingTwo = 1 + // not OK: + z := make(Bar) // compile error: cannot make type Bar + z.thingOne = "hello" + z.thingTwo = 1 + // OK: + x := make(Foo) + x["x"] = "goodbye" + x["y"] = "world" + // not OK: + u := new(Foo) + (*u)["x"] = "goodbye" // !! panic !!: runtime error: assignment to entry in nil map + (*u)["y"] = "world" +} diff --git a/eBook/examples/chapter_10/person.go b/eBook/examples/chapter_10/person.go index 4f60cfb..7b94f4f 100644 --- a/eBook/examples/chapter_10/person.go +++ b/eBook/examples/chapter_10/person.go @@ -1,41 +1,42 @@ -package main - -import ( - "fmt" - "strings" -) - -type Person struct { - firstName string - lastName string -} - -func upPerson (p *Person) { - p.firstName = strings.ToUpper(p.firstName) - p.lastName = strings.ToUpper(p.lastName) -} - -func main() { -// 1- struct as a value type: - var pers1 Person - pers1.firstName = "Chris" - pers1.lastName = "Woodward" - upPerson(&pers1) - fmt.Printf("The name of the person is %s %s\n", pers1.firstName, pers1.lastName) -// 2 - struct as a pointer: - pers2 := new(Person) - pers2.firstName = "Chris" - pers2.lastName = "Woodward" - (*pers2).lastName = "Woodward" - upPerson(pers2) - fmt.Printf("The name of the person is %s %s\n", pers2.firstName, pers2.lastName) -// 3 - struct as a literal: - pers3 := &Person{"Chris","Woodward"} - upPerson(pers3) - fmt.Printf("The name of the person is %s %s\n", pers3.firstName, pers3.lastName) -} -/* 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 -*/ \ No newline at end of file +package main + +import ( + "fmt" + "strings" +) + +type Person struct { + firstName string + lastName string +} + +func upPerson(p *Person) { + p.firstName = strings.ToUpper(p.firstName) + p.lastName = strings.ToUpper(p.lastName) +} + +func main() { + // 1- struct as a value type: + var pers1 Person + pers1.firstName = "Chris" + pers1.lastName = "Woodward" + upPerson(&pers1) + fmt.Printf("The name of the person is %s %s\n", pers1.firstName, pers1.lastName) + // 2 - struct as a pointer: + pers2 := new(Person) + pers2.firstName = "Chris" + pers2.lastName = "Woodward" + (*pers2).lastName = "Woodward" + upPerson(pers2) + fmt.Printf("The name of the person is %s %s\n", pers2.firstName, pers2.lastName) + // 3 - struct as a literal: + pers3 := &Person{"Chris", "Woodward"} + upPerson(pers3) + fmt.Printf("The name of the person is %s %s\n", pers3.firstName, pers3.lastName) +} + +/* 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 +*/ diff --git a/eBook/examples/chapter_10/person2.go b/eBook/examples/chapter_10/person2.go index c58c015..8c309a4 100644 --- a/eBook/examples/chapter_10/person2.go +++ b/eBook/examples/chapter_10/person2.go @@ -1,17 +1,14 @@ -package person - -type Person struct { - firstName string - lastName string -} - -func (p *Person) FirstName() string { - return p.firstName -} - -func (p *Person) SetFirstName(newName string) { - p.firstName = newName -} - - - +package person + +type Person struct { + firstName string + lastName string +} + +func (p *Person) FirstName() string { + return p.firstName +} + +func (p *Person) SetFirstName(newName string) { + p.firstName = newName +} diff --git a/eBook/examples/chapter_10/pointer_value.go b/eBook/examples/chapter_10/pointer_value.go index 253a099..787c560 100644 --- a/eBook/examples/chapter_10/pointer_value.go +++ b/eBook/examples/chapter_10/pointer_value.go @@ -1,28 +1,29 @@ -// pointer_value.go -package main - -import ( - "fmt" -) - -type B struct { - thing int -} - -func (b *B) change() { b.thing = 1 } - -func (b B) write() string { return fmt.Sprint(b) } - -func main() { - var b1 B // b1 is value - b1.change() - fmt.Println(b1.write()) - - b2 := new(B) // b2 is pointer - b2.change() - fmt.Println(b2.write()) -} -/* Output: -{1} -{1} -*/ +// pointer_value.go +package main + +import ( + "fmt" +) + +type B struct { + thing int +} + +func (b *B) change() { b.thing = 1 } + +func (b B) write() string { return fmt.Sprint(b) } + +func main() { + var b1 B // b1 is value + b1.change() + fmt.Println(b1.write()) + + b2 := new(B) // b2 is pointer + b2.change() + fmt.Println(b2.write()) +} + +/* Output: +{1} +{1} +*/ diff --git a/eBook/examples/chapter_10/struct_conversions.go b/eBook/examples/chapter_10/struct_conversions.go index 59ace66..df28fda 100644 --- a/eBook/examples/chapter_10/struct_conversions.go +++ b/eBook/examples/chapter_10/struct_conversions.go @@ -1,24 +1,25 @@ -// struct_conversions.go -package main - -import ( - "fmt" -) - -type number struct { - f float32 -} - -type nr number // alias type - -func main() { - a := number{5.0} - b := nr{5.0} - // var i float32 = b // compile-error: cannot use b (type nr) as type float32 in assignment - // var i = float32(b) // compile-error: cannot convert b (type nr) to type float32 - // var c number = b // compile-error: cannot use b (type nr) as type number in assignment - // needs a conversion: - var c = number(b) - fmt.Println(a, b, c) -} -// output: {5} {5} {5} +// struct_conversions.go +package main + +import ( + "fmt" +) + +type number struct { + f float32 +} + +type nr number // alias type + +func main() { + a := number{5.0} + b := nr{5.0} + // var i float32 = b // compile-error: cannot use b (type nr) as type float32 in assignment + // var i = float32(b) // compile-error: cannot convert b (type nr) to type float32 + // var c number = b // compile-error: cannot use b (type nr) as type number in assignment + // needs a conversion: + var c = number(b) + fmt.Println(a, b, c) +} + +// output: {5} {5} {5} diff --git a/eBook/examples/chapter_10/struct_pack/structPack.go b/eBook/examples/chapter_10/struct_pack/structPack.go index 34fb95c..94d5a9d 100644 --- a/eBook/examples/chapter_10/struct_pack/structPack.go +++ b/eBook/examples/chapter_10/struct_pack/structPack.go @@ -1,6 +1,6 @@ -package structPack - -type ExpStruct struct { - Mi1 int - Mf1 float32 -} +package structPack + +type ExpStruct struct { + Mi1 int + Mf1 float32 +} diff --git a/eBook/examples/chapter_10/struct_tag.go b/eBook/examples/chapter_10/struct_tag.go index d9099d1..dac4b6c 100644 --- a/eBook/examples/chapter_10/struct_tag.go +++ b/eBook/examples/chapter_10/struct_tag.go @@ -1,30 +1,31 @@ -package main - -import ( - "fmt" - "reflect" -) - -type TagType struct { // tags - field1 bool "An important answer" - field2 string "The name of the thing" - field3 int "How much there are" -} - -func main() { - tt := TagType{true, "Barak Obama", 1} - for i:= 0; i < 3; i++ { - refTag(tt, i) - } -} - -func refTag(tt TagType, ix int) { - ttType := reflect.TypeOf(tt) - ixField := ttType.Field(ix) - fmt.Printf("%v\n", ixField.Tag) -} -/* Output: -An important answer -The name of the thing -How much there are -*/ \ No newline at end of file +package main + +import ( + "fmt" + "reflect" +) + +type TagType struct { // tags + field1 bool "An important answer" + field2 string "The name of the thing" + field3 int "How much there are" +} + +func main() { + tt := TagType{true, "Barak Obama", 1} + for i := 0; i < 3; i++ { + refTag(tt, i) + } +} + +func refTag(tt TagType, ix int) { + ttType := reflect.TypeOf(tt) + ixField := ttType.Field(ix) + fmt.Printf("%v\n", ixField.Tag) +} + +/* Output: +An important answer +The name of the thing +How much there are +*/ diff --git a/eBook/examples/chapter_10/structs_anonymous_fields.go b/eBook/examples/chapter_10/structs_anonymous_fields.go index a6a13b2..30f4653 100644 --- a/eBook/examples/chapter_10/structs_anonymous_fields.go +++ b/eBook/examples/chapter_10/structs_anonymous_fields.go @@ -1,34 +1,34 @@ -package main - -import "fmt" - -type innerS struct { - in1 int - in2 int -} - -type outerS struct { - b int - c float32 - int // anonymous field - innerS // anonymous field -} - -func main() { - outer := new(outerS) - outer.b = 6 - outer.c = 7.5 - outer.int = 60 - outer.in1 = 5 - outer.in2 = 10 - - fmt.Printf("outer.b is: %d\n", outer.b) - fmt.Printf("outer.c is: %f\n", outer.c) - fmt.Printf("outer.int is: %d\n", outer.int) - fmt.Printf("outer.in1 is: %d\n", outer.in1) - fmt.Printf("outer.in2 is: %d\n", outer.in2) - // with a struct-literal: - outer2 := outerS{6, 7.5, 60, innerS{5, 10}} - fmt.Println("outer2 is: ", outer2) - -} +package main + +import "fmt" + +type innerS struct { + in1 int + in2 int +} + +type outerS struct { + b int + c float32 + int // anonymous field + innerS // anonymous field +} + +func main() { + outer := new(outerS) + outer.b = 6 + outer.c = 7.5 + outer.int = 60 + outer.in1 = 5 + outer.in2 = 10 + + fmt.Printf("outer.b is: %d\n", outer.b) + fmt.Printf("outer.c is: %f\n", outer.c) + fmt.Printf("outer.int is: %d\n", outer.int) + fmt.Printf("outer.in1 is: %d\n", outer.in1) + fmt.Printf("outer.in2 is: %d\n", outer.in2) + // with a struct-literal: + outer2 := outerS{6, 7.5, 60, innerS{5, 10}} + fmt.Println("outer2 is: ", outer2) + +} diff --git a/eBook/examples/chapter_10/structs_fields.go b/eBook/examples/chapter_10/structs_fields.go index 56d97f3..32ca9c9 100644 --- a/eBook/examples/chapter_10/structs_fields.go +++ b/eBook/examples/chapter_10/structs_fields.go @@ -1,23 +1,23 @@ -package main - -import "fmt" - -type struct1 struct { - i1 int - f1 float32 - str string -} - -func main() { - // var ms *struct1 = new(struct1) - // better: - ms := new(struct1) - ms.i1 = 10 - ms.f1 = 15.5 - ms.str = "Chris" - // ms := &struct1{10, 15.5, "Chris"} - fmt.Printf("The int is: %d\n", ms.i1) - fmt.Printf("The float is: %f\n", ms.f1) - fmt.Printf("The string is: %s\n", ms.str) - fmt.Println(ms) // output: &{10 15.5 Chris} -} +package main + +import "fmt" + +type struct1 struct { + i1 int + f1 float32 + str string +} + +func main() { + // var ms *struct1 = new(struct1) + // better: + ms := new(struct1) + ms.i1 = 10 + ms.f1 = 15.5 + ms.str = "Chris" + // ms := &struct1{10, 15.5, "Chris"} + fmt.Printf("The int is: %d\n", ms.i1) + fmt.Printf("The float is: %f\n", ms.f1) + fmt.Printf("The string is: %s\n", ms.str) + fmt.Println(ms) // output: &{10 15.5 Chris} +} diff --git a/eBook/examples/chapter_10/use_person2.go b/eBook/examples/chapter_10/use_person2.go index 14447d1..27fa70b 100644 --- a/eBook/examples/chapter_10/use_person2.go +++ b/eBook/examples/chapter_10/use_person2.go @@ -1,14 +1,14 @@ -package main - -import ( - "fmt" - "./person" -) - -func main() { - p := new(person.Person) - // error: p.firstName undefined (cannot refer to unexported field or method firstName) - // p.firstName = "Eric" - p.SetFirstName("Eric") - fmt.Println(p.FirstName()) // Output: Eric -} \ No newline at end of file +package main + +import ( + "./person" + "fmt" +) + +func main() { + p := new(person.Person) + // error: p.firstName undefined (cannot refer to unexported field or method firstName) + // p.firstName = "Eric" + p.SetFirstName("Eric") + fmt.Println(p.FirstName()) // Output: Eric +} diff --git a/eBook/examples/chapter_11/cars.go b/eBook/examples/chapter_11/cars.go index 82a56aa..7e6bdd9 100644 --- a/eBook/examples/chapter_11/cars.go +++ b/eBook/examples/chapter_11/cars.go @@ -1,95 +1,94 @@ -// cars.go -package main - -import ( - "fmt" -) - - -type Any interface{} -type Car struct { - Model string - Manufacturer string - BuildYear int - // ... -} -type Cars []*Car - -func main() { - // make some cars: - ford := &Car{"Fiesta","Ford", 2008} - bmw := &Car{"XL 450", "BMW", 2011} - merc := &Car{"D600", "Mercedes", 2009} - bmw2 := &Car{"X 800", "BMW", 2008} - // query: - allCars := Cars([]*Car{ford, bmw, merc, bmw2}) - allNewBMWs := allCars.FindAll(func(car *Car) bool { - return (car.Manufacturer == "BMW") && (car.BuildYear > 2010) - }) - fmt.Println("AllCars: ", allCars) - fmt.Println("New BMWs: ", allNewBMWs) - // - manufacturers := []string{"Ford", "Aston Martin", "Land Rover", "BMW", "Jaguar"} - sortedAppender, sortedCars := MakeSortedAppender(manufacturers) - allCars.Process(sortedAppender) - fmt.Println("Map sortedCars: ", sortedCars) - BMWCount := len(sortedCars["BMW"]) - fmt.Println("We have ", BMWCount, " BMWs") -} - -// Process all cars with the given function f: -func (cs Cars) Process(f func(car *Car)) { - for _, c := range cs { - f(c) - } -} - -// Find all cars matching a given criteria. -func (cs Cars) FindAll(f func(car *Car) bool) Cars { - cars := make([]*Car, 0) - - cs.Process(func(c *Car) { - if f(c) { - cars = append(cars, c) - } - }) - return cars -} - -// Process cars and create new data. -func (cs Cars) Map(f func(car *Car) Any) []Any { - result := make([]Any, 0) - ix := 0 - cs.Process(func(c *Car) { - result[ix] = f(c) - ix++ - }) - return result -} - -func MakeSortedAppender(manufacturers []string) (func(car *Car), map[string]Cars) { - // Prepare maps of sorted cars. - sortedCars := make(map[string]Cars) - - for _, m := range manufacturers { - sortedCars[m] = make([]*Car, 0) - } - sortedCars["Default"] = make([]*Car, 0) - - // Prepare appender function: - appender := func(c *Car) { - if _, ok := sortedCars[c.Manufacturer]; ok { - sortedCars[c.Manufacturer] = append(sortedCars[c.Manufacturer], c) - } else { - sortedCars["Default"] = append(sortedCars["Default"], c) - } - } - return appender, sortedCars -} - -/* Output: -AllCars: [0xf8400038a0 0xf840003bd0 0xf840003ba0 0xf840003b70] -New BMWs: [0xf840003bd0] -Map sortedCars: map[Default:[0xf840003ba0] Jaguar:[] Land Rover:[] BMW:[0xf840003bd0 0xf840003b70] Aston Martin:[] Ford:[0xf8400038a0]] -We have 2 BMWs -*/ +// cars.go +package main + +import ( + "fmt" +) + +type Any interface{} +type Car struct { + Model string + Manufacturer string + BuildYear int + // ... +} +type Cars []*Car + +func main() { + // make some cars: + ford := &Car{"Fiesta", "Ford", 2008} + bmw := &Car{"XL 450", "BMW", 2011} + merc := &Car{"D600", "Mercedes", 2009} + bmw2 := &Car{"X 800", "BMW", 2008} + // query: + allCars := Cars([]*Car{ford, bmw, merc, bmw2}) + allNewBMWs := allCars.FindAll(func(car *Car) bool { + return (car.Manufacturer == "BMW") && (car.BuildYear > 2010) + }) + fmt.Println("AllCars: ", allCars) + fmt.Println("New BMWs: ", allNewBMWs) + // + manufacturers := []string{"Ford", "Aston Martin", "Land Rover", "BMW", "Jaguar"} + sortedAppender, sortedCars := MakeSortedAppender(manufacturers) + allCars.Process(sortedAppender) + fmt.Println("Map sortedCars: ", sortedCars) + BMWCount := len(sortedCars["BMW"]) + fmt.Println("We have ", BMWCount, " BMWs") +} + +// Process all cars with the given function f: +func (cs Cars) Process(f func(car *Car)) { + for _, c := range cs { + f(c) + } +} + +// Find all cars matching a given criteria. +func (cs Cars) FindAll(f func(car *Car) bool) Cars { + cars := make([]*Car, 0) + + cs.Process(func(c *Car) { + if f(c) { + cars = append(cars, c) + } + }) + return cars +} + +// Process cars and create new data. +func (cs Cars) Map(f func(car *Car) Any) []Any { + result := make([]Any, 0) + ix := 0 + cs.Process(func(c *Car) { + result[ix] = f(c) + ix++ + }) + return result +} + +func MakeSortedAppender(manufacturers []string) (func(car *Car), map[string]Cars) { + // Prepare maps of sorted cars. + sortedCars := make(map[string]Cars) + + for _, m := range manufacturers { + sortedCars[m] = make([]*Car, 0) + } + sortedCars["Default"] = make([]*Car, 0) + + // Prepare appender function: + appender := func(c *Car) { + if _, ok := sortedCars[c.Manufacturer]; ok { + sortedCars[c.Manufacturer] = append(sortedCars[c.Manufacturer], c) + } else { + sortedCars["Default"] = append(sortedCars["Default"], c) + } + } + return appender, sortedCars +} + +/* Output: +AllCars: [0xf8400038a0 0xf840003bd0 0xf840003ba0 0xf840003b70] +New BMWs: [0xf840003bd0] +Map sortedCars: map[Default:[0xf840003ba0] Jaguar:[] Land Rover:[] BMW:[0xf840003bd0 0xf840003b70] Aston Martin:[] Ford:[0xf8400038a0]] +We have 2 BMWs +*/ diff --git a/eBook/examples/chapter_11/duck_dance.go b/eBook/examples/chapter_11/duck_dance.go index 43d938e..14be33f 100644 --- a/eBook/examples/chapter_11/duck_dance.go +++ b/eBook/examples/chapter_11/duck_dance.go @@ -1,32 +1,32 @@ -package main - -import "fmt" - -type IDuck interface { - Quack() - Walk() -} - -func DuckDance(duck IDuck) { - for i := 1; i <= 3; i++ { - duck.Quack() - duck.Walk() - } -} - -type Bird struct { - // ... -} - -func (b *Bird) Quack() { - fmt.Println("I am quacking!") -} - -func (b *Bird) Walk() { - fmt.Println("I am walking!") -} - -func main() { - b := new(Bird) - DuckDance(b) -} +package main + +import "fmt" + +type IDuck interface { + Quack() + Walk() +} + +func DuckDance(duck IDuck) { + for i := 1; i <= 3; i++ { + duck.Quack() + duck.Walk() + } +} + +type Bird struct { + // ... +} + +func (b *Bird) Quack() { + fmt.Println("I am quacking!") +} + +func (b *Bird) Walk() { + fmt.Println("I am walking!") +} + +func main() { + b := new(Bird) + DuckDance(b) +} diff --git a/eBook/examples/chapter_11/empty_interface.go b/eBook/examples/chapter_11/empty_interface.go index 6e9358c..af1a210 100644 --- a/eBook/examples/chapter_11/empty_interface.go +++ b/eBook/examples/chapter_11/empty_interface.go @@ -1,38 +1,38 @@ -package main - -import "fmt" - -var i = 5 -var str = "ABC" - -type Person struct { - name string - age int -} - -type Any interface{} - -func main() { - var val Any - val = 5 - fmt.Printf("val has the value: %v\n", val) - val = str - fmt.Printf("val has the value: %v\n", val) - pers1 := new(Person) - pers1.name = "Rob Pike" - pers1.age = 55 - val = pers1 - fmt.Printf("val has the value: %v\n", val) - switch t := val.(type) { - case int: - fmt.Printf("Type int %T\n", t) - case string: - fmt.Printf("Type string %T\n", t) - case bool: - fmt.Printf("Type boolean %T\n", t) - case *Person: - fmt.Printf("Type pointer to Person %T\n", *t) - default: - fmt.Printf("Unexpected type %T", t) - } -} +package main + +import "fmt" + +var i = 5 +var str = "ABC" + +type Person struct { + name string + age int +} + +type Any interface{} + +func main() { + var val Any + val = 5 + fmt.Printf("val has the value: %v\n", val) + val = str + fmt.Printf("val has the value: %v\n", val) + pers1 := new(Person) + pers1.name = "Rob Pike" + pers1.age = 55 + val = pers1 + fmt.Printf("val has the value: %v\n", val) + switch t := val.(type) { + case int: + fmt.Printf("Type int %T\n", t) + case string: + fmt.Printf("Type string %T\n", t) + case bool: + fmt.Printf("Type boolean %T\n", t) + case *Person: + fmt.Printf("Type pointer to Person %T\n", *t) + default: + fmt.Printf("Unexpected type %T", t) + } +} diff --git a/eBook/examples/chapter_11/emptyint_switch.go b/eBook/examples/chapter_11/emptyint_switch.go index d034dad..ddbd807 100644 --- a/eBook/examples/chapter_11/emptyint_switch.go +++ b/eBook/examples/chapter_11/emptyint_switch.go @@ -29,4 +29,5 @@ func TypeSwitch() { func main() { TypeSwitch() } + // Output: any hello is a special String! diff --git a/eBook/examples/chapter_11/interfaces.go b/eBook/examples/chapter_11/interfaces.go index 5c15bd3..aee89c7 100644 --- a/eBook/examples/chapter_11/interfaces.go +++ b/eBook/examples/chapter_11/interfaces.go @@ -1,30 +1,31 @@ -package main - -import "fmt" - -type Shaper interface { - Area() float32 - // Perimeter() float32 -} - -type Square struct { - side float32 -} - -func (sq *Square) Area() float32 { - return sq.side * sq.side -} - -func main() { - sq1 := new(Square) - sq1.side = 5 - - // var areaIntf Shaper - // areaIntf = sq1 - // shorter, without separate declaration: - // areaIntf := Shaper(sq1) - // or even: - areaIntf := sq1 - fmt.Printf("The square has area: %f\n", areaIntf.Area()) -} -// The square has area: 25.000000 +package main + +import "fmt" + +type Shaper interface { + Area() float32 + // Perimeter() float32 +} + +type Square struct { + side float32 +} + +func (sq *Square) Area() float32 { + return sq.side * sq.side +} + +func main() { + sq1 := new(Square) + sq1.side = 5 + + // var areaIntf Shaper + // areaIntf = sq1 + // shorter, without separate declaration: + // areaIntf := Shaper(sq1) + // or even: + areaIntf := sq1 + fmt.Printf("The square has area: %f\n", areaIntf.Area()) +} + +// The square has area: 25.000000 diff --git a/eBook/examples/chapter_11/interfaces_poly.go b/eBook/examples/chapter_11/interfaces_poly.go index 80efb4c..1b84cec 100644 --- a/eBook/examples/chapter_11/interfaces_poly.go +++ b/eBook/examples/chapter_11/interfaces_poly.go @@ -1,45 +1,43 @@ -// interfaces_poly.go -package main - -import "fmt" - -type Shaper interface { - Area() float32 -} - -type Square struct { - side float32 -} - -func (sq *Square) Area() float32 { - return sq.side * sq.side -} - -type Rectangle struct { - length, width float32 -} - -func (r Rectangle) Area() float32 { - return r.length * r.width -} - -func main() { - r := Rectangle{5, 3} // Area() of Rectangle needs a value - q := &Square{5} // Area() of Square needs a pointer - shapes := []Shaper{r, q} - fmt.Println("Looping through shapes for area ...") - for n, _ := range shapes { - fmt.Println("Shape details: ", shapes[n]) - fmt.Println("Area of this shape is: ", shapes[n].Area()) - } -} -/* Output: -Looping through shapes for area ... -Shape details: {5 3} -Area of this shape is: 15 -Shape details: &{5} -Area of this shape is: 25 -*/ - - - +// interfaces_poly.go +package main + +import "fmt" + +type Shaper interface { + Area() float32 +} + +type Square struct { + side float32 +} + +func (sq *Square) Area() float32 { + return sq.side * sq.side +} + +type Rectangle struct { + length, width float32 +} + +func (r Rectangle) Area() float32 { + return r.length * r.width +} + +func main() { + r := Rectangle{5, 3} // Area() of Rectangle needs a value + q := &Square{5} // Area() of Square needs a pointer + shapes := []Shaper{r, q} + fmt.Println("Looping through shapes for area ...") + for n := range shapes { + fmt.Println("Shape details: ", shapes[n]) + fmt.Println("Area of this shape is: ", shapes[n].Area()) + } +} + +/* Output: +Looping through shapes for area ... +Shape details: {5 3} +Area of this shape is: 15 +Shape details: &{5} +Area of this shape is: 25 +*/ diff --git a/eBook/examples/chapter_11/methodset2.go b/eBook/examples/chapter_11/methodset2.go index 886c687..408489a 100644 --- a/eBook/examples/chapter_11/methodset2.go +++ b/eBook/examples/chapter_11/methodset2.go @@ -1,48 +1,49 @@ -// methodset2.go -package main - -import ( - "fmt" -) - -type List []int -func (l List) Len() int { return len(l) } -func (l *List) Append(val int) { *l = append(*l, val) } - -type Appender interface { - Append(int) -} - -func CountInto(a Appender, start, end int) { - for i := start; i <= end; i++ { - a.Append(i) - } -} - -type Lener interface { - Len() int -} - -func LongEnough(l Lener) bool { - return l.Len()*10 > 42 -} - -func main() { - // A bare value - var lst List - // compiler error: - // cannot use lst (type List) as type Appender in function argument: - // List does not implement Appender (Append method requires pointer receiver) - // CountInto(lst, 1, 10) // INVALID: Append has a pointer receiver - - if LongEnough(lst) { // VALID: Identical receiver type - fmt.Printf(" - lst is long enough") - } - - // A pointer value - plst := new(List) - CountInto(plst, 1, 10) // VALID: Identical receiver type - if LongEnough(plst) { // VALID: a *List can be dereferenced for the receiver - fmt.Printf(" - plst is long enough") // - plst is long enoug - } -} +// methodset2.go +package main + +import ( + "fmt" +) + +type List []int + +func (l List) Len() int { return len(l) } +func (l *List) Append(val int) { *l = append(*l, val) } + +type Appender interface { + Append(int) +} + +func CountInto(a Appender, start, end int) { + for i := start; i <= end; i++ { + a.Append(i) + } +} + +type Lener interface { + Len() int +} + +func LongEnough(l Lener) bool { + return l.Len()*10 > 42 +} + +func main() { + // A bare value + var lst List + // compiler error: + // cannot use lst (type List) as type Appender in function argument: + // List does not implement Appender (Append method requires pointer receiver) + // CountInto(lst, 1, 10) // INVALID: Append has a pointer receiver + + if LongEnough(lst) { // VALID: Identical receiver type + fmt.Printf(" - lst is long enough") + } + + // A pointer value + plst := new(List) + CountInto(plst, 1, 10) // VALID: Identical receiver type + if LongEnough(plst) { // VALID: a *List can be dereferenced for the receiver + fmt.Printf(" - plst is long enough") // - plst is long enoug + } +} diff --git a/eBook/examples/chapter_11/multi_interfaces_poly.go b/eBook/examples/chapter_11/multi_interfaces_poly.go index d98db8c..a8c9663 100644 --- a/eBook/examples/chapter_11/multi_interfaces_poly.go +++ b/eBook/examples/chapter_11/multi_interfaces_poly.go @@ -1,65 +1,66 @@ -//multi_interfaces_poly.go -package main - -import "fmt" - -type Shaper interface { - Area() float32 -} - -type TopologicalGenus interface { - Rank() int -} - -type Square struct { - side float32 -} - -func (sq *Square) Area() float32 { - return sq.side * sq.side -} - -func (sq *Square) Rank() int { - return 1 -} - -type Rectangle struct { - length, width float32 -} - -func (r Rectangle) Area() float32 { - return r.length * r.width -} - -func (r Rectangle) Rank() int { - return 2 -} - -func main() { - r := Rectangle{5, 3} // Area() of Rectangle needs a value - q := &Square{5} // Area() of Square needs a pointer - shapes := []Shaper{r, q} - fmt.Println("Looping through shapes for area ...") - for n, _ := range shapes { - fmt.Println("Shape details: ", shapes[n]) - fmt.Println("Area of this shape is: ", shapes[n].Area()) - } - topgen := []TopologicalGenus{r, q} - fmt.Println("Looping through topgen for rank ...") - for n, _ := range topgen { - fmt.Println("Shape details: ", topgen[n]) - fmt.Println("Topological Genus of this shape is: ", topgen[n].Rank()) - } -} -/* Output: -Looping through shapes for area ... -Shape details: {5 3} -Area of this shape is: 15 -Shape details: &{5} -Area of this shape is: 25 -Looping through topgen for rank ... -Shape details: {5 3} -Topological Genus of this shape is: 2 -Shape details: &{5} -Topological Genus of this shape is: 1 -*/ +//multi_interfaces_poly.go +package main + +import "fmt" + +type Shaper interface { + Area() float32 +} + +type TopologicalGenus interface { + Rank() int +} + +type Square struct { + side float32 +} + +func (sq *Square) Area() float32 { + return sq.side * sq.side +} + +func (sq *Square) Rank() int { + return 1 +} + +type Rectangle struct { + length, width float32 +} + +func (r Rectangle) Area() float32 { + return r.length * r.width +} + +func (r Rectangle) Rank() int { + return 2 +} + +func main() { + r := Rectangle{5, 3} // Area() of Rectangle needs a value + q := &Square{5} // Area() of Square needs a pointer + shapes := []Shaper{r, q} + fmt.Println("Looping through shapes for area ...") + for n := range shapes { + fmt.Println("Shape details: ", shapes[n]) + fmt.Println("Area of this shape is: ", shapes[n].Area()) + } + topgen := []TopologicalGenus{r, q} + fmt.Println("Looping through topgen for rank ...") + for n := range topgen { + fmt.Println("Shape details: ", topgen[n]) + fmt.Println("Topological Genus of this shape is: ", topgen[n].Rank()) + } +} + +/* Output: +Looping through shapes for area ... +Shape details: {5 3} +Area of this shape is: 15 +Shape details: &{5} +Area of this shape is: 25 +Looping through topgen for rank ... +Shape details: {5 3} +Topological Genus of this shape is: 2 +Shape details: &{5} +Topological Genus of this shape is: 1 +*/ diff --git a/eBook/examples/chapter_11/node_structures.go b/eBook/examples/chapter_11/node_structures.go index f729d39..e6fa97c 100644 --- a/eBook/examples/chapter_11/node_structures.go +++ b/eBook/examples/chapter_11/node_structures.go @@ -1,31 +1,31 @@ -// node_structures.go -package main - -import "fmt" - -type Node struct { - le *Node - data interface{} - ri *Node -} - -func NewNode(left, right *Node) *Node { - return &Node{left, nil, right} -} - -func (n *Node) SetData(data interface{}) { - n.data = data -} - -func main() { - root := NewNode(nil,nil) - root.SetData("root node") - // make child (leaf) nodes: - a := NewNode(nil,nil) - a.SetData("left node") - b := NewNode(nil,nil) - b.SetData("right node") - root.le = a - root.ri = b - fmt.Printf("%v\n", root) // Output: &{0x125275f0 root node 0x125275e0} -} +// node_structures.go +package main + +import "fmt" + +type Node struct { + le *Node + data interface{} + ri *Node +} + +func NewNode(left, right *Node) *Node { + return &Node{left, nil, right} +} + +func (n *Node) SetData(data interface{}) { + n.data = data +} + +func main() { + root := NewNode(nil, nil) + root.SetData("root node") + // make child (leaf) nodes: + a := NewNode(nil, nil) + a.SetData("left node") + b := NewNode(nil, nil) + b.SetData("right node") + root.le = a + root.ri = b + fmt.Printf("%v\n", root) // Output: &{0x125275f0 root node 0x125275e0} +} diff --git a/eBook/examples/chapter_11/print.go b/eBook/examples/chapter_11/print.go index a394902..29062d9 100644 --- a/eBook/examples/chapter_11/print.go +++ b/eBook/examples/chapter_11/print.go @@ -1,43 +1,50 @@ -// 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 \ No newline at end of file +// 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 diff --git a/eBook/examples/chapter_11/reflect1.go b/eBook/examples/chapter_11/reflect1.go index 7e0526b..9f8d822 100644 --- a/eBook/examples/chapter_11/reflect1.go +++ b/eBook/examples/chapter_11/reflect1.go @@ -1,32 +1,33 @@ -// reflect1.go -// blog: Laws of Reflection -package main - -import ( - "fmt" - "reflect" -) - -func main() { - var x float64 = 3.4 - fmt.Println("type:", reflect.TypeOf(x)) - v := reflect.ValueOf(x) - fmt.Println("value:", v) - fmt.Println("type:", v.Type()) - fmt.Println("kind:", v.Kind()) - fmt.Println("value:", v.Float()) - fmt.Println(v.Interface()) - fmt.Printf("value is %5.2e\n", v.Interface()) - y := v.Interface().(float64) - fmt.Println(y) -} -/* output: -type: float64 -value: -type: float64 -kind: float64 -value: 3.4 -3.4 -value is 3.40e+00 -3.4 -*/ +// reflect1.go +// blog: Laws of Reflection +package main + +import ( + "fmt" + "reflect" +) + +func main() { + var x float64 = 3.4 + fmt.Println("type:", reflect.TypeOf(x)) + v := reflect.ValueOf(x) + fmt.Println("value:", v) + fmt.Println("type:", v.Type()) + fmt.Println("kind:", v.Kind()) + fmt.Println("value:", v.Float()) + fmt.Println(v.Interface()) + fmt.Printf("value is %5.2e\n", v.Interface()) + y := v.Interface().(float64) + fmt.Println(y) +} + +/* output: +type: float64 +value: +type: float64 +kind: float64 +value: 3.4 +3.4 +value is 3.40e+00 +3.4 +*/ diff --git a/eBook/examples/chapter_11/reflect2.go b/eBook/examples/chapter_11/reflect2.go index 7780228..bac0ea0 100644 --- a/eBook/examples/chapter_11/reflect2.go +++ b/eBook/examples/chapter_11/reflect2.go @@ -1,33 +1,34 @@ -// reflect2.go -package main - -import ( - "fmt" - "reflect" -) - -func main() { - var x float64 = 3.4 - v := reflect.ValueOf(x) - // setting a value: - // v.SetFloat(3.1415) // Error: will panic: reflect.Value.SetFloat using unaddressable value - fmt.Println("settability of v:", v.CanSet()) - v = reflect.ValueOf(&x) // Note: take the address of x. - fmt.Println("type of v:", v.Type()) - fmt.Println("settability of v:", v.CanSet()) - v = v.Elem() - fmt.Println("The Elem of v is: ", v) - fmt.Println("settability of v:", v.CanSet()) - v.SetFloat(3.1415) // this works! - fmt.Println(v.Interface()) - fmt.Println(v) -} -/* Output: -settability of v: false -type of v: *float64 -settability of v: false -The Elem of v is: -settability of v: true -3.1415 - -*/ +// reflect2.go +package main + +import ( + "fmt" + "reflect" +) + +func main() { + var x float64 = 3.4 + v := reflect.ValueOf(x) + // setting a value: + // v.SetFloat(3.1415) // Error: will panic: reflect.Value.SetFloat using unaddressable value + fmt.Println("settability of v:", v.CanSet()) + v = reflect.ValueOf(&x) // Note: take the address of x. + fmt.Println("type of v:", v.Type()) + fmt.Println("settability of v:", v.CanSet()) + v = v.Elem() + fmt.Println("The Elem of v is: ", v) + fmt.Println("settability of v:", v.CanSet()) + v.SetFloat(3.1415) // this works! + fmt.Println(v.Interface()) + fmt.Println(v) +} + +/* Output: +settability of v: false +type of v: *float64 +settability of v: false +The Elem of v is: +settability of v: true +3.1415 + +*/ diff --git a/eBook/examples/chapter_11/reflect_struct.go b/eBook/examples/chapter_11/reflect_struct.go index 2d95a25..962f866 100644 --- a/eBook/examples/chapter_11/reflect_struct.go +++ b/eBook/examples/chapter_11/reflect_struct.go @@ -1,47 +1,48 @@ -// reflect.go -package main - -import ( - "fmt" - "reflect" -) - -type NotknownType struct { - s1, s2, s3 string -} - -func (n NotknownType) String() string { - return n.s1 + " - " + n.s2 + " - " + n.s3 -} - -// variable to investigate: -var secret interface {} = NotknownType{"Ada", "Go", "Oberon"} - -func main() { - value := reflect.ValueOf(secret) // - typ := reflect.TypeOf(secret) // main.NotknownType - // alternative: - //typ := value.Type() // main.NotknownType - fmt.Println(typ) - knd := value.Kind() // struct - fmt.Println(knd) - - // iterate through the fields of the struct: - for i:= 0; i < value.NumField(); i++ { - fmt.Printf("Field %d: %v\n", i, value.Field(i)) - // error: panic: reflect.Value.SetString using value obtained using unexported field - //value.Field(i).SetString("C#") - } - - // call the first method, which is String(): - results := value.Method(0).Call(nil) - fmt.Println(results) // [Ada - Go - Oberon] -} -/* Output: -main.NotknownType -struct -Field 0: Ada -Field 1: Go -Field 2: Oberon -[Ada - Go - Oberon] -*/ \ No newline at end of file +// reflect.go +package main + +import ( + "fmt" + "reflect" +) + +type NotknownType struct { + s1, s2, s3 string +} + +func (n NotknownType) String() string { + return n.s1 + " - " + n.s2 + " - " + n.s3 +} + +// variable to investigate: +var secret interface{} = NotknownType{"Ada", "Go", "Oberon"} + +func main() { + value := reflect.ValueOf(secret) // + typ := reflect.TypeOf(secret) // main.NotknownType + // alternative: + //typ := value.Type() // main.NotknownType + fmt.Println(typ) + knd := value.Kind() // struct + fmt.Println(knd) + + // iterate through the fields of the struct: + for i := 0; i < value.NumField(); i++ { + fmt.Printf("Field %d: %v\n", i, value.Field(i)) + // error: panic: reflect.Value.SetString using value obtained using unexported field + //value.Field(i).SetString("C#") + } + + // call the first method, which is String(): + results := value.Method(0).Call(nil) + fmt.Println(results) // [Ada - Go - Oberon] +} + +/* Output: +main.NotknownType +struct +Field 0: Ada +Field 1: Go +Field 2: Oberon +[Ada - Go - Oberon] +*/ diff --git a/eBook/examples/chapter_11/reflect_struct2.go b/eBook/examples/chapter_11/reflect_struct2.go index 2c0c915..d5296fe 100644 --- a/eBook/examples/chapter_11/reflect_struct2.go +++ b/eBook/examples/chapter_11/reflect_struct2.go @@ -1,31 +1,32 @@ -// reflect_struct2.go -package main - -import ( - "fmt" - "reflect" -) - -type T struct { - A int - B string -} - -func main() { - t := T{23, "skidoo"} - s := reflect.ValueOf(&t).Elem() - typeOfT := s.Type() - for i := 0; i < s.NumField(); i++ { - f := s.Field(i) - fmt.Printf("%d: %s %s = %v\n", i, - typeOfT.Field(i).Name, f.Type(), f.Interface()) - } - s.Field(0).SetInt(77) - s.Field(1).SetString("Sunset Strip") - fmt.Println("t is now", t) -} -/* Output: -0: A int = 23 -1: B string = skidoo -t is now {77 Sunset Strip} -*/ +// reflect_struct2.go +package main + +import ( + "fmt" + "reflect" +) + +type T struct { + A int + B string +} + +func main() { + t := T{23, "skidoo"} + s := reflect.ValueOf(&t).Elem() + typeOfT := s.Type() + for i := 0; i < s.NumField(); i++ { + f := s.Field(i) + fmt.Printf("%d: %s %s = %v\n", i, + typeOfT.Field(i).Name, f.Type(), f.Interface()) + } + s.Field(0).SetInt(77) + s.Field(1).SetString("Sunset Strip") + fmt.Println("t is now", t) +} + +/* Output: +0: A int = 23 +1: B string = skidoo +t is now {77 Sunset Strip} +*/ diff --git a/eBook/examples/chapter_11/sort/sort.go b/eBook/examples/chapter_11/sort/sort.go index 00f618d..dcb4e5a 100644 --- a/eBook/examples/chapter_11/sort/sort.go +++ b/eBook/examples/chapter_11/sort/sort.go @@ -1,58 +1,60 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Sorting using a general interface -package sort - -// Sorting interface -type Interface interface { - Len() int - Less(i, j int) bool - Swap(i, j int) -} - -// General sort function -func Sort(data Interface) { - for i := 1; i < data.Len(); i++ { - for j := i; j > 0 && data.Less(j, j-1); j-- { - data.Swap(j, j-1) - } - } -} - -// Test if data is sorted -func IsSorted(data Interface) bool { - n := data.Len() - for i := n - 1; i > 0; i-- { - if data.Less(i, i-1) { - return false - } - } - return true -} - -// Convenience types for common cases: IntArray -type IntArray []int - -func (p IntArray) Len() int { return len(p) } -func (p IntArray) Less(i, j int) bool { return p[i] < p[j] } -func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -type Float64Array []float64 -func (p Float64Array) Len() int { return len(p) } -func (p Float64Array) Less(i, j int) bool { return p[i] < p[j] } -func (p Float64Array) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -type StringArray []string -func (p StringArray) Len() int { return len(p) } -func (p StringArray) Less(i, j int) bool { return p[i] < p[j] } -func (p StringArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -// Convenience wrappers for common cases -func SortInts(a []int) { Sort(IntArray(a)) } -func SortFloat64s(a []float64) { Sort(Float64Array(a)) } -func SortStrings(a []string) { Sort(StringArray(a)) } - -func IntsAreSorted(a []int) bool { return IsSorted(IntArray(a)) } -func Float64sAreSorted(a []float64) bool { return IsSorted(Float64Array(a)) } -func StringsAreSorted(a []string) bool { return IsSorted(StringArray(a)) } \ No newline at end of file +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// Sorting using a general interface +package sort + +// Sorting interface +type Interface interface { + Len() int + Less(i, j int) bool + Swap(i, j int) +} + +// General sort function +func Sort(data Interface) { + for i := 1; i < data.Len(); i++ { + for j := i; j > 0 && data.Less(j, j-1); j-- { + data.Swap(j, j-1) + } + } +} + +// Test if data is sorted +func IsSorted(data Interface) bool { + n := data.Len() + for i := n - 1; i > 0; i-- { + if data.Less(i, i-1) { + return false + } + } + return true +} + +// Convenience types for common cases: IntArray +type IntArray []int + +func (p IntArray) Len() int { return len(p) } +func (p IntArray) Less(i, j int) bool { return p[i] < p[j] } +func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +type Float64Array []float64 + +func (p Float64Array) Len() int { return len(p) } +func (p Float64Array) Less(i, j int) bool { return p[i] < p[j] } +func (p Float64Array) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +type StringArray []string + +func (p StringArray) Len() int { return len(p) } +func (p StringArray) Less(i, j int) bool { return p[i] < p[j] } +func (p StringArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +// Convenience wrappers for common cases +func SortInts(a []int) { Sort(IntArray(a)) } +func SortFloat64s(a []float64) { Sort(Float64Array(a)) } +func SortStrings(a []string) { Sort(StringArray(a)) } + +func IntsAreSorted(a []int) bool { return IsSorted(IntArray(a)) } +func Float64sAreSorted(a []float64) bool { return IsSorted(Float64Array(a)) } +func StringsAreSorted(a []string) bool { return IsSorted(StringArray(a)) } diff --git a/eBook/examples/chapter_11/sortmain.go b/eBook/examples/chapter_11/sortmain.go index da63508..20fd389 100644 --- a/eBook/examples/chapter_11/sortmain.go +++ b/eBook/examples/chapter_11/sortmain.go @@ -1,82 +1,81 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This package gives an example of how to use a custom package with interfaces -package main - -import ( - "fmt" - "./sort" -) - -// sorting of slice of integers -func ints() { - data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586} - a := sort.IntArray(data) //conversion to type IntArray - sort.Sort(a) - if !sort.IsSorted(a) { - panic("fail") - } - fmt.Printf("The sorted array is: %v\n", a) -} - -// sorting of slice of strings -func strings() { - data := []string{"monday", "friday", "tuesday", "wednesday", "sunday","thursday", "", "saturday"} - a := sort.StringArray(data) - sort.Sort(a) - if !sort.IsSorted(a) { - panic("fail") - } - fmt.Printf("The sorted array is: %v\n", a) -} - -// a type which describes a day of the week -type day struct { - num int - shortName string - longName string -} - -type dayArray struct { - data []*day -} - -func (p *dayArray) Len() int { return len(p.data) } -func (p *dayArray) Less(i, j int) bool { return p.data[i].num < p.data[j].num } -func (p *dayArray) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i] } - -// sorting of custom type day -func days() { - Sunday := day{0, "SUN", "Sunday"} - Monday := day{1, "MON", "Monday"} - Tuesday := day{2, "TUE", "Tuesday"} - Wednesday := day{3, "WED", "Wednesday"} - Thursday := day{4, "THU", "Thursday"} - Friday := day{5, "FRI", "Friday"} - Saturday := day{6, "SAT", "Saturday"} - data := []*day{&Tuesday, &Thursday, &Wednesday, &Sunday, &Monday, &Friday, &Saturday} - a := dayArray{data} - sort.Sort(&a) - if !sort.IsSorted(&a) { - panic("fail") - } - for _, d := range data { - fmt.Printf("%s ", d.longName) - } - fmt.Printf("\n") -} - - -func main() { - ints() - strings() - days() -} - -/* Output: -The sorted array is: [-5467984 -784 0 0 42 59 74 238 905 959 7586 7586 9845] -The sorted array is: [ friday monday saturday sunday thursday tuesday wednesday] -Sunday Monday Tuesday Wednesday Thursday Friday Saturday -*/ \ No newline at end of file +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This package gives an example of how to use a custom package with interfaces +package main + +import ( + "./sort" + "fmt" +) + +// sorting of slice of integers +func ints() { + data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586} + a := sort.IntArray(data) //conversion to type IntArray + sort.Sort(a) + if !sort.IsSorted(a) { + panic("fail") + } + fmt.Printf("The sorted array is: %v\n", a) +} + +// sorting of slice of strings +func strings() { + data := []string{"monday", "friday", "tuesday", "wednesday", "sunday", "thursday", "", "saturday"} + a := sort.StringArray(data) + sort.Sort(a) + if !sort.IsSorted(a) { + panic("fail") + } + fmt.Printf("The sorted array is: %v\n", a) +} + +// a type which describes a day of the week +type day struct { + num int + shortName string + longName string +} + +type dayArray struct { + data []*day +} + +func (p *dayArray) Len() int { return len(p.data) } +func (p *dayArray) Less(i, j int) bool { return p.data[i].num < p.data[j].num } +func (p *dayArray) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i] } + +// sorting of custom type day +func days() { + Sunday := day{0, "SUN", "Sunday"} + Monday := day{1, "MON", "Monday"} + Tuesday := day{2, "TUE", "Tuesday"} + Wednesday := day{3, "WED", "Wednesday"} + Thursday := day{4, "THU", "Thursday"} + Friday := day{5, "FRI", "Friday"} + Saturday := day{6, "SAT", "Saturday"} + data := []*day{&Tuesday, &Thursday, &Wednesday, &Sunday, &Monday, &Friday, &Saturday} + a := dayArray{data} + sort.Sort(&a) + if !sort.IsSorted(&a) { + panic("fail") + } + for _, d := range data { + fmt.Printf("%s ", d.longName) + } + fmt.Printf("\n") +} + +func main() { + ints() + strings() + days() +} + +/* Output: +The sorted array is: [-5467984 -784 0 0 42 59 74 238 905 959 7586 7586 9845] +The sorted array is: [ friday monday saturday sunday thursday tuesday wednesday] +Sunday Monday Tuesday Wednesday Thursday Friday Saturday +*/ diff --git a/eBook/examples/chapter_11/static.go b/eBook/examples/chapter_11/static.go index 032ba04..aca2b75 100644 --- a/eBook/examples/chapter_11/static.go +++ b/eBook/examples/chapter_11/static.go @@ -1,23 +1,23 @@ -// static.go -package main - -import ( - "io" - "os" - "bufio" - "bytes" - "fmt" -) - -var r io.Reader - -func main() { - r = os.Stdin - r = bufio.NewReader(r) - r = new(bytes.Buffer) - f, _ := os.Open("test.txt") - r = bufio.NewReader(f) - var s *bytes.Buffer = new(bytes.Buffer) - r = s - fmt.Println(s) -} +// static.go +package main + +import ( + "bufio" + "bytes" + "fmt" + "io" + "os" +) + +var r io.Reader + +func main() { + r = os.Stdin + r = bufio.NewReader(r) + r = new(bytes.Buffer) + f, _ := os.Open("test.txt") + r = bufio.NewReader(f) + var s *bytes.Buffer = new(bytes.Buffer) + r = s + fmt.Println(s) +} diff --git a/eBook/examples/chapter_11/tideland-cgl.googlecode.com/hg/cgl.go b/eBook/examples/chapter_11/tideland-cgl.googlecode.com/hg/cgl.go index 295e4c7..b5c63ad 100644 --- a/eBook/examples/chapter_11/tideland-cgl.googlecode.com/hg/cgl.go +++ b/eBook/examples/chapter_11/tideland-cgl.googlecode.com/hg/cgl.go @@ -43,8 +43,8 @@ package cgl import ( "bytes" "crypto/rand" - "fmt" "encoding/hex" + "fmt" "io" "log" "reflect" @@ -120,7 +120,7 @@ func (uuid UUID) String() string { // MORE ID FUNCTIONS //-------------------- -// LimitedSepIdentifier builds an identifier out of multiple parts, +// LimitedSepIdentifier builds an identifier out of multiple parts, // all as lowercase strings and concatenated with the separator // Non letters and digits are exchanged with dashes and // reduced to a maximum of one each. If limit is true only @@ -173,8 +173,8 @@ func Identifier(parts ...interface{}) string { return SepIdentifier(":", parts...) } -// TypeAsIdentifierPart transforms the name of the arguments type into -// a part for identifiers. It's splitted at each uppercase char, +// TypeAsIdentifierPart transforms the name of the arguments type into +// a part for identifiers. It's splitted at each uppercase char, // concatenated with dashes and transferred to lowercase. func TypeAsIdentifierPart(i interface{}) string { var buf bytes.Buffer diff --git a/eBook/examples/chapter_11/tideland-cgl.googlecode.com/hg/cglmon.go b/eBook/examples/chapter_11/tideland-cgl.googlecode.com/hg/cglmon.go index 6747358..ea8ef4e 100644 --- a/eBook/examples/chapter_11/tideland-cgl.googlecode.com/hg/cglmon.go +++ b/eBook/examples/chapter_11/tideland-cgl.googlecode.com/hg/cglmon.go @@ -151,7 +151,7 @@ func (sm *SystemMonitor) MeasuringPointsMap(f func(*MeasuringPoint) interface{}) return resp.([]interface{}) } -// MeasuringPointsDo performs the function f for +// MeasuringPointsDo performs the function f for // all measuring points. func (sm *SystemMonitor) MeasuringPointsDo(f func(*MeasuringPoint)) { cmd := &command{cmdMeasuringPointsDo, f, nil} @@ -450,7 +450,7 @@ type Measuring struct { endTime int64 } -// EndMEasuring ends a measuring and passes it to the +// EndMEasuring ends a measuring and passes it to the // measuring server in the background. func (m *Measuring) EndMeasuring() int64 { m.endTime = time.Nanoseconds() diff --git a/eBook/examples/chapter_11/type_interfaces.go b/eBook/examples/chapter_11/type_interfaces.go index 9042428..37d5235 100644 --- a/eBook/examples/chapter_11/type_interfaces.go +++ b/eBook/examples/chapter_11/type_interfaces.go @@ -1,62 +1,62 @@ -package main - -import ( - "fmt" - "math" -) - -type Square struct { - side float32 -} - -type Circle struct { - radius float32 -} - -type Shaper interface { - Area() float32 -} - -func main() { - var areaIntf Shaper - sq1 := new(Square) - sq1.side = 5 - - areaIntf = sq1 - // Is Square the type of areaIntf ? - if t, ok := areaIntf.(*Square); ok { - fmt.Printf("The type of areaIntf is: %T\n", t) - } - if u, ok := areaIntf.(*Circle); ok { - fmt.Printf("The type of areaIntf is: %T\n", u) - } else { - fmt.Println("areaIntf does not contain a variable of type Circle") - } - // testing with switch: - switch t := areaIntf.(type) { - case *Square: - fmt.Printf("Type Square %T with value %v\n", t, t) - case *Circle: - fmt.Printf("Type Circle %T with value %v\n", t, t) - /* - case bool: - fmt.Printf("Type boolean %t\n", t) - case int: - fmt.Printf("Type int %d\n", t) - case *bool: - fmt.Printf("Type pointer to boolean %t\n", *t) - case *int: - fmt.Printf("Type pointer to int %d\n", *t) - */ - default: - fmt.Printf("Unexpected type %T", t) - } -} - -func (sq *Square) Area() float32 { - return sq.side * sq.side -} - -func (ci *Circle) Area() float32 { - return ci.radius * ci.radius * math.Pi -} +package main + +import ( + "fmt" + "math" +) + +type Square struct { + side float32 +} + +type Circle struct { + radius float32 +} + +type Shaper interface { + Area() float32 +} + +func main() { + var areaIntf Shaper + sq1 := new(Square) + sq1.side = 5 + + areaIntf = sq1 + // Is Square the type of areaIntf ? + if t, ok := areaIntf.(*Square); ok { + fmt.Printf("The type of areaIntf is: %T\n", t) + } + if u, ok := areaIntf.(*Circle); ok { + fmt.Printf("The type of areaIntf is: %T\n", u) + } else { + fmt.Println("areaIntf does not contain a variable of type Circle") + } + // testing with switch: + switch t := areaIntf.(type) { + case *Square: + fmt.Printf("Type Square %T with value %v\n", t, t) + case *Circle: + fmt.Printf("Type Circle %T with value %v\n", t, t) + /* + case bool: + fmt.Printf("Type boolean %t\n", t) + case int: + fmt.Printf("Type int %d\n", t) + case *bool: + fmt.Printf("Type pointer to boolean %t\n", *t) + case *int: + fmt.Printf("Type pointer to int %d\n", *t) + */ + default: + fmt.Printf("Unexpected type %T", t) + } +} + +func (sq *Square) Area() float32 { + return sq.side * sq.side +} + +func (ci *Circle) Area() float32 { + return ci.radius * ci.radius * math.Pi +} diff --git a/eBook/examples/chapter_12/cat.go b/eBook/examples/chapter_12/cat.go index 2e2abe7..7b1627d 100644 --- a/eBook/examples/chapter_12/cat.go +++ b/eBook/examples/chapter_12/cat.go @@ -1,36 +1,35 @@ -package main - -import ( - "os" - "io" - "fmt" - "bufio" - "flag" -) - -func cat(r *bufio.Reader) { - for { - buf, err := r.ReadBytes('\n') - if err == io.EOF { - break - } - fmt.Fprintf(os.Stdout, "%s", buf) - } - return -} - -func main() { - flag.Parse() - if flag.NArg() == 0 { - cat(bufio.NewReader(os.Stdin)) - } - for i := 0; i < flag.NArg(); i++ { - f, err := os.Open(flag.Arg(i)) - if err != nil { - fmt.Fprintf(os.Stderr, "%s:error reading from %s: %s\n", os.Args[0], flag.Arg(i), err.Error()) - continue - } - cat(bufio.NewReader(f)) - } -} - +package main + +import ( + "bufio" + "flag" + "fmt" + "io" + "os" +) + +func cat(r *bufio.Reader) { + for { + buf, err := r.ReadBytes('\n') + if err == io.EOF { + break + } + fmt.Fprintf(os.Stdout, "%s", buf) + } + return +} + +func main() { + flag.Parse() + if flag.NArg() == 0 { + cat(bufio.NewReader(os.Stdin)) + } + for i := 0; i < flag.NArg(); i++ { + f, err := os.Open(flag.Arg(i)) + if err != nil { + fmt.Fprintf(os.Stderr, "%s:error reading from %s: %s\n", os.Args[0], flag.Arg(i), err.Error()) + continue + } + cat(bufio.NewReader(f)) + } +} diff --git a/eBook/examples/chapter_12/cat2.go b/eBook/examples/chapter_12/cat2.go index 8bb2538..39a4c66 100644 --- a/eBook/examples/chapter_12/cat2.go +++ b/eBook/examples/chapter_12/cat2.go @@ -1,41 +1,41 @@ -package main - -import ( - "flag" - "fmt" - "os" -) - -func cat(f *os.File) { - const NBUF = 512 - var buf [NBUF]byte - for { - switch nr, err := f.Read(buf[:]); true { - case nr < 0: - fmt.Fprintf(os.Stderr, "cat: error reading: %s\n", err.Error()) - os.Exit(1) - case nr == 0: // EOF - return - case nr > 0: - if nw, ew := os.Stdout.Write(buf[0:nr]); nw != nr { - fmt.Fprintf(os.Stderr, "cat: error writing: %s\n", ew.Error()) - } - } - } -} - -func main() { - flag.Parse() // Scans the arg list and sets up flags - if flag.NArg() == 0 { - cat(os.Stdin) - } - for i := 0; i < flag.NArg(); i++ { - f, err := os.Open(flag.Arg(i)) - if f == nil { - fmt.Fprintf(os.Stderr, "cat: can't open %s: error %s\n", flag.Arg(i), err) - os.Exit(1) - } - cat(f) - f.Close() - } -} +package main + +import ( + "flag" + "fmt" + "os" +) + +func cat(f *os.File) { + const NBUF = 512 + var buf [NBUF]byte + for { + switch nr, err := f.Read(buf[:]); true { + case nr < 0: + fmt.Fprintf(os.Stderr, "cat: error reading: %s\n", err.Error()) + os.Exit(1) + case nr == 0: // EOF + return + case nr > 0: + if nw, ew := os.Stdout.Write(buf[0:nr]); nw != nr { + fmt.Fprintf(os.Stderr, "cat: error writing: %s\n", ew.Error()) + } + } + } +} + +func main() { + flag.Parse() // Scans the arg list and sets up flags + if flag.NArg() == 0 { + cat(os.Stdin) + } + for i := 0; i < flag.NArg(); i++ { + f, err := os.Open(flag.Arg(i)) + if f == nil { + fmt.Fprintf(os.Stderr, "cat: can't open %s: error %s\n", flag.Arg(i), err) + os.Exit(1) + } + cat(f) + f.Close() + } +} diff --git a/eBook/examples/chapter_12/echo.go b/eBook/examples/chapter_12/echo.go index 3424772..dd2adac 100644 --- a/eBook/examples/chapter_12/echo.go +++ b/eBook/examples/chapter_12/echo.go @@ -1,29 +1,29 @@ -package main - -import ( - "os" - "flag" // command line option parser -) - -var NewLine = flag.Bool("n", false, "print newline") // echo -n flag, of type *bool - -const ( - Space = " " - Newline = "\n" -) - -func main() { - flag.PrintDefaults() - flag.Parse() // Scans the arg list and sets up flags - var s string = "" - for i := 0; i < flag.NArg(); i++ { - if i > 0 { - s += " " - if *NewLine { // -n is parsed, flag becomes true - s += Newline - } - } - s += flag.Arg(i) - } - os.Stdout.WriteString(s) -} +package main + +import ( + "flag" // command line option parser + "os" +) + +var NewLine = flag.Bool("n", false, "print newline") // echo -n flag, of type *bool + +const ( + Space = " " + Newline = "\n" +) + +func main() { + flag.PrintDefaults() + flag.Parse() // Scans the arg list and sets up flags + var s string = "" + for i := 0; i < flag.NArg(); i++ { + if i > 0 { + s += " " + if *NewLine { // -n is parsed, flag becomes true + s += Newline + } + } + s += flag.Arg(i) + } + os.Stdout.WriteString(s) +} diff --git a/eBook/examples/chapter_12/filecopy.go b/eBook/examples/chapter_12/filecopy.go index 2cad9af..ddda3b6 100644 --- a/eBook/examples/chapter_12/filecopy.go +++ b/eBook/examples/chapter_12/filecopy.go @@ -1,29 +1,29 @@ -// filecopy.go -package main - -import ( - "fmt" - "io" - "os" -) - -func main() { - CopyFile("target.txt", "source.txt") - fmt.Println("Copy done!") -} - -func CopyFile(dstName, srcName string) (written int64, err error) { - src, err := os.Open(srcName) - if err != nil { - return - } - defer src.Close() - - dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644) - if err != nil { - return - } - defer dst.Close() - - return io.Copy(dst, src) -} +// filecopy.go +package main + +import ( + "fmt" + "io" + "os" +) + +func main() { + CopyFile("target.txt", "source.txt") + fmt.Println("Copy done!") +} + +func CopyFile(dstName, srcName string) (written int64, err error) { + src, err := os.Open(srcName) + if err != nil { + return + } + defer src.Close() + + dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644) + if err != nil { + return + } + defer dst.Close() + + return io.Copy(dst, src) +} diff --git a/eBook/examples/chapter_12/fileinput.go b/eBook/examples/chapter_12/fileinput.go index d7644d0..f1fea98 100644 --- a/eBook/examples/chapter_12/fileinput.go +++ b/eBook/examples/chapter_12/fileinput.go @@ -1,34 +1,34 @@ -package main - -import ( - "bufio" - "fmt" - "io" - "os" -) - -func main() { - // var inputFile *os.File - // var inputError, readerError os.Error - // var inputReader *bufio.Reader - // var inputString string - - inputFile, inputError := os.Open("input.dat") - if inputError != nil { - fmt.Printf("An error occurred on opening the inputfile\n" + - "Does the file exist?\n" + - "Have you got acces to it?\n") - return // exit the function on error - } - defer inputFile.Close() - - inputReader := bufio.NewReader(inputFile) - - for { - inputString, readerError := inputReader.ReadString('\n') - if readerError == io.EOF { - return // error or EOF - } - fmt.Printf("The input was: %s", inputString) - } -} +package main + +import ( + "bufio" + "fmt" + "io" + "os" +) + +func main() { + // var inputFile *os.File + // var inputError, readerError os.Error + // var inputReader *bufio.Reader + // var inputString string + + inputFile, inputError := os.Open("input.dat") + if inputError != nil { + fmt.Printf("An error occurred on opening the inputfile\n" + + "Does the file exist?\n" + + "Have you got acces to it?\n") + return // exit the function on error + } + defer inputFile.Close() + + inputReader := bufio.NewReader(inputFile) + + for { + inputString, readerError := inputReader.ReadString('\n') + if readerError == io.EOF { + return // error or EOF + } + fmt.Printf("The input was: %s", inputString) + } +} diff --git a/eBook/examples/chapter_12/fileoutput.go b/eBook/examples/chapter_12/fileoutput.go index 50c283e..2638c05 100644 --- a/eBook/examples/chapter_12/fileoutput.go +++ b/eBook/examples/chapter_12/fileoutput.go @@ -1,28 +1,28 @@ -package main - -import ( - "os" - "bufio" - "fmt" -) - -func main () { - // var outputWriter *bufio.Writer - // var outputFile *os.File - // var outputError os.Error - // var outputString string - outputFile, outputError := os.OpenFile("output.dat", os.O_WRONLY|os.O_CREATE, 0666) - if outputError != nil { - fmt.Printf("An error occurred with file opening or creation\n") - return - } - defer outputFile.Close() - - outputWriter := bufio.NewWriter(outputFile) - outputString := "hello world!\n" - - for i:=0; i<10; i++ { - outputWriter.WriteString(outputString) - } - outputWriter.Flush() -} \ No newline at end of file +package main + +import ( + "bufio" + "fmt" + "os" +) + +func main() { + // var outputWriter *bufio.Writer + // var outputFile *os.File + // var outputError os.Error + // var outputString string + outputFile, outputError := os.OpenFile("output.dat", os.O_WRONLY|os.O_CREATE, 0666) + if outputError != nil { + fmt.Printf("An error occurred with file opening or creation\n") + return + } + defer outputFile.Close() + + outputWriter := bufio.NewWriter(outputFile) + outputString := "hello world!\n" + + for i := 0; i < 10; i++ { + outputWriter.WriteString(outputString) + } + outputWriter.Flush() +} diff --git a/eBook/examples/chapter_12/filewrite.go b/eBook/examples/chapter_12/filewrite.go index 7863d5e..cb3e1a5 100644 --- a/eBook/examples/chapter_12/filewrite.go +++ b/eBook/examples/chapter_12/filewrite.go @@ -1,10 +1,10 @@ -package main - -import "os" - -func main() { - os.Stdout.WriteString("hello, world\n") - f, _ := os.OpenFile("test", os.O_CREATE|os.O_WRONLY, 0) - defer f.Close() - f.WriteString("hello, world in a file\n") -} +package main + +import "os" + +func main() { + os.Stdout.WriteString("hello, world\n") + f, _ := os.OpenFile("test", os.O_CREATE|os.O_WRONLY, 0) + defer f.Close() + f.WriteString("hello, world in a file\n") +} diff --git a/eBook/examples/chapter_12/gob1.go b/eBook/examples/chapter_12/gob1.go index 918a23d..f0db6ab 100644 --- a/eBook/examples/chapter_12/gob1.go +++ b/eBook/examples/chapter_12/gob1.go @@ -1,41 +1,42 @@ -// gob1.go -package main - -import ( - "bytes" - "fmt" - "encoding/gob" - "log" -) - -type P struct { - X, Y, Z int - Name string -} - -type Q struct { - X, Y *int32 - Name string -} - -func main() { - // Initialize the encoder and decoder. Normally enc and dec would be - // bound to network connections and the encoder and decoder would - // run in different processes. - var network bytes.Buffer // Stand-in for a network connection - enc := gob.NewEncoder(&network) // Will write to network. - dec := gob.NewDecoder(&network) // Will read from network. - // Encode (send) the value. - err := enc.Encode(P{3, 4, 5, "Pythagoras"}) - if err != nil { - log.Fatal("encode error:", err) - } - // Decode (receive) the value. - var q Q - err = dec.Decode(&q) - if err != nil { - log.Fatal("decode error:", err) - } - fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y) -} -// Output: "Pythagoras": {3,4} +// gob1.go +package main + +import ( + "bytes" + "encoding/gob" + "fmt" + "log" +) + +type P struct { + X, Y, Z int + Name string +} + +type Q struct { + X, Y *int32 + Name string +} + +func main() { + // Initialize the encoder and decoder. Normally enc and dec would be + // bound to network connections and the encoder and decoder would + // run in different processes. + var network bytes.Buffer // Stand-in for a network connection + enc := gob.NewEncoder(&network) // Will write to network. + dec := gob.NewDecoder(&network) // Will read from network. + // Encode (send) the value. + err := enc.Encode(P{3, 4, 5, "Pythagoras"}) + if err != nil { + log.Fatal("encode error:", err) + } + // Decode (receive) the value. + var q Q + err = dec.Decode(&q) + if err != nil { + log.Fatal("decode error:", err) + } + fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y) +} + +// Output: "Pythagoras": {3,4} diff --git a/eBook/examples/chapter_12/gob2.go b/eBook/examples/chapter_12/gob2.go index 70690c9..fefc4bf 100644 --- a/eBook/examples/chapter_12/gob2.go +++ b/eBook/examples/chapter_12/gob2.go @@ -1,39 +1,38 @@ -// gob2.go -package main - -import ( - "encoding/gob" - "log" - "os" -) - -type Address struct { - Type string - City string - Country string -} - -type VCard struct { - FirstName string - LastName string - Addresses []*Address - Remark string -} - -var content string - -func main() { - pa := &Address{"private", "Aartselaar","Belgium"} - wa := &Address{"work", "Boom", "Belgium"} - vc := VCard{"Jan", "Kersschot", []*Address{pa,wa}, "none"} - // fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none}: - // using an encoder: - file, _ := os.OpenFile("vcard.gob", os.O_CREATE|os.O_WRONLY, 0666) - defer file.Close() - enc := gob.NewEncoder(file) - err := enc.Encode(vc) - if err != nil { - log.Println("Error in encoding gob") - } -} - +// gob2.go +package main + +import ( + "encoding/gob" + "log" + "os" +) + +type Address struct { + Type string + City string + Country string +} + +type VCard struct { + FirstName string + LastName string + Addresses []*Address + Remark string +} + +var content string + +func main() { + pa := &Address{"private", "Aartselaar", "Belgium"} + wa := &Address{"work", "Boom", "Belgium"} + vc := VCard{"Jan", "Kersschot", []*Address{pa, wa}, "none"} + // fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none}: + // using an encoder: + file, _ := os.OpenFile("vcard.gob", os.O_CREATE|os.O_WRONLY, 0666) + defer file.Close() + enc := gob.NewEncoder(file) + err := enc.Encode(vc) + if err != nil { + log.Println("Error in encoding gob") + } +} diff --git a/eBook/examples/chapter_12/gzipped.go b/eBook/examples/chapter_12/gzipped.go index 2666f43..aa9e5a5 100644 --- a/eBook/examples/chapter_12/gzipped.go +++ b/eBook/examples/chapter_12/gzipped.go @@ -1,35 +1,35 @@ -// gzipped.go -package main - -import ( - "fmt" - "bufio" - "os" - "compress/gzip" -) - -func main() { - fName := "MyFile.gz" - var r *bufio.Reader - fi, err := os.Open(fName) - if err != nil { - fmt.Fprintf(os.Stderr, "%v, Can't open %s: error: %s\n", os.Args[0], fName, - err) - os.Exit(1) - } - fz, err := gzip.NewReader(fi) - if err != nil { - r = bufio.NewReader(fi) - } else { - r = bufio.NewReader(fz) - } - - for { - line, err := r.ReadString('\n') - if err != nil { - fmt.Println("Done reading file") - os.Exit(0) - } - fmt.Println(line) - } -} +// gzipped.go +package main + +import ( + "bufio" + "compress/gzip" + "fmt" + "os" +) + +func main() { + fName := "MyFile.gz" + var r *bufio.Reader + fi, err := os.Open(fName) + if err != nil { + fmt.Fprintf(os.Stderr, "%v, Can't open %s: error: %s\n", os.Args[0], fName, + err) + os.Exit(1) + } + fz, err := gzip.NewReader(fi) + if err != nil { + r = bufio.NewReader(fi) + } else { + r = bufio.NewReader(fz) + } + + for { + line, err := r.ReadString('\n') + if err != nil { + fmt.Println("Done reading file") + os.Exit(0) + } + fmt.Println(line) + } +} diff --git a/eBook/examples/chapter_12/hash_sha1.go b/eBook/examples/chapter_12/hash_sha1.go index d22c8ae..fb19b71 100644 --- a/eBook/examples/chapter_12/hash_sha1.go +++ b/eBook/examples/chapter_12/hash_sha1.go @@ -1,31 +1,32 @@ -// hash_sha1.go -package main - -import ( - "fmt" - "crypto/sha1" - "io" - "log" -) - -func main() { - hasher := sha1.New() - io.WriteString(hasher, "test") - b := []byte{} - fmt.Printf("Result: %x\n", hasher.Sum(b)) - fmt.Printf("Result: %d\n", hasher.Sum(b)) - // - hasher.Reset() - data := []byte("We shall overcome!") - n, err := hasher.Write(data) - if n!=len(data) || err!=nil { - log.Printf("Hash write error: %v / %v", n, err) - } - checksum := hasher.Sum(b) - fmt.Printf("Result: %x\n", checksum) -} -/* Output: -Result: a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 -Result: [169 74 143 229 204 177 155 166 28 76 8 115 211 145 233 135 152 47 187 211] -Result: e2222bfc59850bbb00a722e764a555603bb59b2a -*/ +// hash_sha1.go +package main + +import ( + "crypto/sha1" + "fmt" + "io" + "log" +) + +func main() { + hasher := sha1.New() + io.WriteString(hasher, "test") + b := []byte{} + fmt.Printf("Result: %x\n", hasher.Sum(b)) + fmt.Printf("Result: %d\n", hasher.Sum(b)) + // + hasher.Reset() + data := []byte("We shall overcome!") + n, err := hasher.Write(data) + if n != len(data) || err != nil { + log.Printf("Hash write error: %v / %v", n, err) + } + checksum := hasher.Sum(b) + fmt.Printf("Result: %x\n", checksum) +} + +/* Output: +Result: a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 +Result: [169 74 143 229 204 177 155 166 28 76 8 115 211 145 233 135 152 47 187 211] +Result: e2222bfc59850bbb00a722e764a555603bb59b2a +*/ diff --git a/eBook/examples/chapter_12/io_interfaces.go b/eBook/examples/chapter_12/io_interfaces.go index 165d9f1..db0985c 100644 --- a/eBook/examples/chapter_12/io_interfaces.go +++ b/eBook/examples/chapter_12/io_interfaces.go @@ -1,18 +1,18 @@ -// interfaces being used in the GO-package fmt -package main - -import ( - "bufio" - "fmt" - "os" -) - -func main() { - // unbuffered - fmt.Fprintf(os.Stdout, "%s\n", "hello world! - unbuffered") - // buffered: os.Stdout implements io.Writer - buf := bufio.NewWriter(os.Stdout) - // and now so does buf. - fmt.Fprintf(buf, "%s\n", "hello world! - buffered") - buf.Flush() -} +// interfaces being used in the GO-package fmt +package main + +import ( + "bufio" + "fmt" + "os" +) + +func main() { + // unbuffered + fmt.Fprintf(os.Stdout, "%s\n", "hello world! - unbuffered") + // buffered: os.Stdout implements io.Writer + buf := bufio.NewWriter(os.Stdout) + // and now so does buf. + fmt.Fprintf(buf, "%s\n", "hello world! - buffered") + buf.Flush() +} diff --git a/eBook/examples/chapter_12/json.go b/eBook/examples/chapter_12/json.go index f2e691d..9d91239 100644 --- a/eBook/examples/chapter_12/json.go +++ b/eBook/examples/chapter_12/json.go @@ -1,40 +1,40 @@ -// json.go -package main - -import ( - "fmt" - "encoding/json" - "log" - "os" -) - -type Address struct { - Type string - City string - Country string -} - -type VCard struct { - FirstName string - LastName string - Addresses []*Address - Remark string -} - -func main() { - pa := &Address{"private", "Aartselaar","Belgium"} - wa := &Address{"work", "Boom", "Belgium"} - vc := VCard{"Jan", "Kersschot", []*Address{pa,wa}, "none"} - // fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none}: - // JSON format: - js, _ := json.Marshal(vc) - fmt.Printf("JSON format: %s", js) - // using an encoder: - file, _ := os.OpenFile("vcard.json", os.O_CREATE|os.O_WRONLY, 0) - defer file.Close() - enc := json.NewEncoder(file) - err := enc.Encode(vc) - if err != nil { - log.Println("Error in encoding json") - } -} +// json.go +package main + +import ( + "encoding/json" + "fmt" + "log" + "os" +) + +type Address struct { + Type string + City string + Country string +} + +type VCard struct { + FirstName string + LastName string + Addresses []*Address + Remark string +} + +func main() { + pa := &Address{"private", "Aartselaar", "Belgium"} + wa := &Address{"work", "Boom", "Belgium"} + vc := VCard{"Jan", "Kersschot", []*Address{pa, wa}, "none"} + // fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none}: + // JSON format: + js, _ := json.Marshal(vc) + fmt.Printf("JSON format: %s", js) + // using an encoder: + file, _ := os.OpenFile("vcard.json", os.O_CREATE|os.O_WRONLY, 0) + defer file.Close() + enc := json.NewEncoder(file) + err := enc.Encode(vc) + if err != nil { + log.Println("Error in encoding json") + } +} diff --git a/eBook/examples/chapter_12/json_xml_case.go b/eBook/examples/chapter_12/json_xml_case.go index 9c320e2..654ea6b 100644 --- a/eBook/examples/chapter_12/json_xml_case.go +++ b/eBook/examples/chapter_12/json_xml_case.go @@ -1,54 +1,55 @@ -// json_xml_case.go -package main - -import ( - "encoding/json" - "encoding/xml" - "fmt" - "log" - "strings" -) - -type thing struct { - Field1 int - Field2 string -} - -func main() { - x := `423hello from xml` - j := `{"field1": 423, "field2": "hello from json"}` - - tx := thing{} - if err := xml.Unmarshal(strings.NewReader(x), &tx); err != nil { - log.Fatalf("Error unmarshaling XML: %v", err) - } - - tj := thing{} - if err := json.Unmarshal([]byte(j), &tj); err != nil { - log.Fatalf("Error unmarshaling JSON: %v", err) - } - - fmt.Printf("From JSON: %#v\n", tj) - fmt.Printf("From XML: %#v\n", tx) - -} -/* Output with -type thing struct { - Field1 int - Field2 string -}: - -From XML: main.thing{Field1:0, Field2:""} // All matching is case sensitive! -From JSON: main.thing{Field1:423, Field2:"hello from json"} - -Output with -type thing struct { - field1 int - field2 string -}: - -2012/02/22 10:51:11 Error unmarshaling JSON: json: cannot unmarshal object -field1" into unexported field field1 of type main.thing - -JSON uses reflection to unmarshal! -*/ \ No newline at end of file +// json_xml_case.go +package main + +import ( + "encoding/json" + "encoding/xml" + "fmt" + "log" + "strings" +) + +type thing struct { + Field1 int + Field2 string +} + +func main() { + x := `423hello from xml` + j := `{"field1": 423, "field2": "hello from json"}` + + tx := thing{} + if err := xml.Unmarshal(strings.NewReader(x), &tx); err != nil { + log.Fatalf("Error unmarshaling XML: %v", err) + } + + tj := thing{} + if err := json.Unmarshal([]byte(j), &tj); err != nil { + log.Fatalf("Error unmarshaling JSON: %v", err) + } + + fmt.Printf("From JSON: %#v\n", tj) + fmt.Printf("From XML: %#v\n", tx) + +} + +/* Output with +type thing struct { + Field1 int + Field2 string +}: + +From XML: main.thing{Field1:0, Field2:""} // All matching is case sensitive! +From JSON: main.thing{Field1:423, Field2:"hello from json"} + +Output with +type thing struct { + field1 int + field2 string +}: + +2012/02/22 10:51:11 Error unmarshaling JSON: json: cannot unmarshal object +field1" into unexported field field1 of type main.thing + +JSON uses reflection to unmarshal! +*/ diff --git a/eBook/examples/chapter_12/os_args.go b/eBook/examples/chapter_12/os_args.go index 7dc9aa9..83a8d2a 100644 --- a/eBook/examples/chapter_12/os_args.go +++ b/eBook/examples/chapter_12/os_args.go @@ -1,16 +1,16 @@ -// os_args.go -package main - -import ( - "fmt" - "os" - "strings" -) - -func main() { - who := "Alice " - if len(os.Args) > 1 { - who += strings.Join(os.Args[1:], " ") - } - fmt.Println("Good Morning", who) -} +// os_args.go +package main + +import ( + "fmt" + "os" + "strings" +) + +func main() { + who := "Alice " + if len(os.Args) > 1 { + who += strings.Join(os.Args[1:], " ") + } + fmt.Println("Good Morning", who) +} diff --git a/eBook/examples/chapter_12/read_file2.go b/eBook/examples/chapter_12/read_file2.go index 59e4397..bd8b87c 100644 --- a/eBook/examples/chapter_12/read_file2.go +++ b/eBook/examples/chapter_12/read_file2.go @@ -1,38 +1,39 @@ -// read_csvfile.go -package main - -import ( - "fmt" - "os" -// "io/ioutil" -// "strings" -) - -func main() { - file, err := os.Open("products2.txt") - if err != nil { - panic(err) - } - defer file.Close() - - var col1, col2, col3 []string - for { - var v1, v2, v3 string - _, err := fmt.Fscanln(file, &v1, &v2, &v3) - if err != nil { - break - } - col1 = append(col1, v1) - col2 = append(col2, v2) - col3 = append(col3, v3) - } - - fmt.Println(col1) - fmt.Println(col2) - fmt.Println(col3) -} -/* Output: -[ABC FUNC GO] -[40 56 45] -[150 280 356] -*/ \ No newline at end of file +// read_csvfile.go +package main + +import ( + "fmt" + "os" + // "io/ioutil" + // "strings" +) + +func main() { + file, err := os.Open("products2.txt") + if err != nil { + panic(err) + } + defer file.Close() + + var col1, col2, col3 []string + for { + var v1, v2, v3 string + _, err := fmt.Fscanln(file, &v1, &v2, &v3) + if err != nil { + break + } + col1 = append(col1, v1) + col2 = append(col2, v2) + col3 = append(col3, v3) + } + + fmt.Println(col1) + fmt.Println(col2) + fmt.Println(col3) +} + +/* Output: +[ABC FUNC GO] +[40 56 45] +[150 280 356] +*/ diff --git a/eBook/examples/chapter_12/read_files.go b/eBook/examples/chapter_12/read_files.go index 2c37e95..74ff6f7 100644 --- a/eBook/examples/chapter_12/read_files.go +++ b/eBook/examples/chapter_12/read_files.go @@ -1,30 +1,28 @@ -// read_files.go -package main - -import ( - "bufio" - "flag" - "fmt" - "io" - "os" -) - -func main() { - fmt.Printf("Reading files...\n") - flag.Parse() - - for i := 0; i < flag.NArg(); i++ { - fmt.Printf("[File: %v]\n", flag.Arg(i)) - fin, err := os.Open(flag.Arg(i)) - if err != nil { - fmt.Printf("The file %v does not exist!\n", flag.Arg(i)) - break - } - r := bufio.NewReader(fin) - for line, _, err := r.ReadLine(); - err != io.EOF; - line, _, err = r.ReadLine() { - fmt.Printf("Lines: %v (error %v)\n", string(line), err) - } - } -} +// read_files.go +package main + +import ( + "bufio" + "flag" + "fmt" + "io" + "os" +) + +func main() { + fmt.Printf("Reading files...\n") + flag.Parse() + + for i := 0; i < flag.NArg(); i++ { + fmt.Printf("[File: %v]\n", flag.Arg(i)) + fin, err := os.Open(flag.Arg(i)) + if err != nil { + fmt.Printf("The file %v does not exist!\n", flag.Arg(i)) + break + } + r := bufio.NewReader(fin) + for line, _, err := r.ReadLine(); err != io.EOF; line, _, err = r.ReadLine() { + fmt.Printf("Lines: %v (error %v)\n", string(line), err) + } + } +} diff --git a/eBook/examples/chapter_12/read_write_file1.go b/eBook/examples/chapter_12/read_write_file1.go index b6138a7..88f0168 100644 --- a/eBook/examples/chapter_12/read_write_file1.go +++ b/eBook/examples/chapter_12/read_write_file1.go @@ -1,21 +1,21 @@ -// read_write_file.go -package main - -import ( - "fmt" - "io/ioutil" -) - -func main() { - inputFile := "products.txt" - outputFile := "products_copy.txt" - buf, err := ioutil.ReadFile(inputFile) - if err != nil { - panic(err.Error()) - } - fmt.Printf("%s\n", string(buf)) - err = ioutil.WriteFile(outputFile, buf, 0644) // oct, not hex - if err != nil { - panic(err.Error()) - } -} +// read_write_file.go +package main + +import ( + "fmt" + "io/ioutil" +) + +func main() { + inputFile := "products.txt" + outputFile := "products_copy.txt" + buf, err := ioutil.ReadFile(inputFile) + if err != nil { + panic(err.Error()) + } + fmt.Printf("%s\n", string(buf)) + err = ioutil.WriteFile(outputFile, buf, 0644) // oct, not hex + if err != nil { + panic(err.Error()) + } +} diff --git a/eBook/examples/chapter_12/readinput1.go b/eBook/examples/chapter_12/readinput1.go index 175401c..defa351 100644 --- a/eBook/examples/chapter_12/readinput1.go +++ b/eBook/examples/chapter_12/readinput1.go @@ -1,24 +1,24 @@ -// read input from the console: -package main - -import ( - "fmt" -) - -var ( - firstName, lastName, s string - i int - f float32 - input = "56.12 / 5212 / Go" - format = "%f / %d / %s" -) - -func main() { - fmt.Println("Please enter your full name: ") - fmt.Scanln(&firstName, &lastName) - // fmt.Scanf("%s %s", &firstName, &lastName) - fmt.Printf("Hi %s %s!\n", firstName, lastName) // Hi Chris Naegels - - fmt.Sscanf(input, format, &f, &i, &s) - fmt.Println("From the string we read: ", f, i, s) // From the string we read: 56.12 5212 Go -} +// read input from the console: +package main + +import ( + "fmt" +) + +var ( + firstName, lastName, s string + i int + f float32 + input = "56.12 / 5212 / Go" + format = "%f / %d / %s" +) + +func main() { + fmt.Println("Please enter your full name: ") + fmt.Scanln(&firstName, &lastName) + // fmt.Scanf("%s %s", &firstName, &lastName) + fmt.Printf("Hi %s %s!\n", firstName, lastName) // Hi Chris Naegels + + fmt.Sscanf(input, format, &f, &i, &s) + fmt.Println("From the string we read: ", f, i, s) // From the string we read: 56.12 5212 Go +} diff --git a/eBook/examples/chapter_12/readinput2.go b/eBook/examples/chapter_12/readinput2.go index 21be89a..7611e97 100644 --- a/eBook/examples/chapter_12/readinput2.go +++ b/eBook/examples/chapter_12/readinput2.go @@ -1,22 +1,22 @@ -// read input from the console: -package main - -import ( - "fmt" - "bufio" - "os" -) - -var inputReader *bufio.Reader - var input string - var err error - -func main() { - inputReader = bufio.NewReader(os.Stdin) // reader for input - fmt.Println("Please enter some input: ") - input, err = inputReader.ReadString('\n') - - if err == nil { - fmt.Printf("The input was: %s\n", input) - } -} +// read input from the console: +package main + +import ( + "bufio" + "fmt" + "os" +) + +var inputReader *bufio.Reader +var input string +var err error + +func main() { + inputReader = bufio.NewReader(os.Stdin) // reader for input + fmt.Println("Please enter some input: ") + input, err = inputReader.ReadString('\n') + + if err == nil { + fmt.Printf("The input was: %s\n", input) + } +} diff --git a/eBook/examples/chapter_12/switch_input.go b/eBook/examples/chapter_12/switch_input.go index 99e606b..762cb3b 100644 --- a/eBook/examples/chapter_12/switch_input.go +++ b/eBook/examples/chapter_12/switch_input.go @@ -1,41 +1,51 @@ -package main - -import ( - "fmt" - "os" - "bufio" -) - -func main() { - inputReader := bufio.NewReader(os.Stdin) - fmt.Println("Please enter your name:") - input, err := inputReader.ReadString('\n') - - if err != nil { - fmt.Println("There were errors reading, exiting program.") - return - } - - fmt.Printf("Your name is %s", input) - // For Unix: test with delimiter "\n", for Windows: test with "\r\n" - switch input { - case "Philip\r\n": fmt.Println("Welcome Philip!") - case "Chris\r\n": fmt.Println("Welcome Chris!") - case "Ivo\r\n": fmt.Println("Welcome Ivo!") - default: fmt.Printf("You are not welcome here! Goodbye!") - } - - // version 2: - switch input { - case "Philip\r\n": fallthrough - case "Ivo\r\n": fallthrough - case "Chris\r\n": fmt.Printf("Welcome %s\n", input) - default: fmt.Printf("You are not welcome here! Goodbye!\n") - } - - // version 3: - switch input { - case "Philip\r\n", "Ivo\r\n": fmt.Printf("Welcome %s\n", input) - default: fmt.Printf("You are not welcome here! Goodbye!\n") - } -} +package main + +import ( + "bufio" + "fmt" + "os" +) + +func main() { + inputReader := bufio.NewReader(os.Stdin) + fmt.Println("Please enter your name:") + input, err := inputReader.ReadString('\n') + + if err != nil { + fmt.Println("There were errors reading, exiting program.") + return + } + + fmt.Printf("Your name is %s", input) + // For Unix: test with delimiter "\n", for Windows: test with "\r\n" + switch input { + case "Philip\r\n": + fmt.Println("Welcome Philip!") + case "Chris\r\n": + fmt.Println("Welcome Chris!") + case "Ivo\r\n": + fmt.Println("Welcome Ivo!") + default: + fmt.Printf("You are not welcome here! Goodbye!") + } + + // version 2: + switch input { + case "Philip\r\n": + fallthrough + case "Ivo\r\n": + fallthrough + case "Chris\r\n": + fmt.Printf("Welcome %s\n", input) + default: + fmt.Printf("You are not welcome here! Goodbye!\n") + } + + // version 3: + switch input { + case "Philip\r\n", "Ivo\r\n": + fmt.Printf("Welcome %s\n", input) + default: + fmt.Printf("You are not welcome here! Goodbye!\n") + } +} diff --git a/eBook/examples/chapter_12/xml.go b/eBook/examples/chapter_12/xml.go index 0082aab..9d65edc 100644 --- a/eBook/examples/chapter_12/xml.go +++ b/eBook/examples/chapter_12/xml.go @@ -1,49 +1,50 @@ -// xml.go -package main - -import ( - "fmt" - "strings" - "encoding/xml" -) - -var t, token xml.Token -var err error - -func main() { - input := "LauraLynn" - inputReader := strings.NewReader(input) - p := xml.NewDecoder(inputReader) - - for t, err = p.Token(); err == nil; t, err = p.Token() { - switch token := t.(type) { - case xml.StartElement: - name := token.Name.Local - fmt.Printf("Token name: %s\n", name) - for _, attr := range token.Attr { - attrName := attr.Name.Local - attrValue := attr.Value - fmt.Printf("An attribute is: %s %s\n", attrName, attrValue) - // ... - } - case xml.EndElement: - fmt.Println("End of token") - case xml.CharData: - content := string([]byte(token)) - fmt.Printf("This is the content: %v\n", content ) - // ... - default: - // ... - } - } -} -/* Output: -Token name: Person -Token name: FirstName -This is the content: Laura -End of token -Token name: LastName -This is the content: Lynn -End of token -End of token -*/ +// xml.go +package main + +import ( + "encoding/xml" + "fmt" + "strings" +) + +var t, token xml.Token +var err error + +func main() { + input := "LauraLynn" + inputReader := strings.NewReader(input) + p := xml.NewDecoder(inputReader) + + for t, err = p.Token(); err == nil; t, err = p.Token() { + switch token := t.(type) { + case xml.StartElement: + name := token.Name.Local + fmt.Printf("Token name: %s\n", name) + for _, attr := range token.Attr { + attrName := attr.Name.Local + attrValue := attr.Value + fmt.Printf("An attribute is: %s %s\n", attrName, attrValue) + // ... + } + case xml.EndElement: + fmt.Println("End of token") + case xml.CharData: + content := string([]byte(token)) + fmt.Printf("This is the content: %v\n", content) + // ... + default: + // ... + } + } +} + +/* Output: +Token name: Person +Token name: FirstName +This is the content: Laura +End of token +Token name: LastName +This is the content: Lynn +End of token +End of token +*/ diff --git a/eBook/examples/chapter_13/errors.go b/eBook/examples/chapter_13/errors.go index 442c2bc..b1c5332 100644 --- a/eBook/examples/chapter_13/errors.go +++ b/eBook/examples/chapter_13/errors.go @@ -1,14 +1,15 @@ -// errors.go -package main - -import ( - "errors" - "fmt" -) - -var errNotFound error = errors.New("Not found error") - -func main() { - fmt.Printf("error: %v", errNotFound) -} -// error: Not found error \ No newline at end of file +// errors.go +package main + +import ( + "errors" + "fmt" +) + +var errNotFound error = errors.New("Not found error") + +func main() { + fmt.Printf("error: %v", errNotFound) +} + +// error: Not found error diff --git a/eBook/examples/chapter_13/even/even/even.go b/eBook/examples/chapter_13/even/even/even.go index 204c443..2d50125 100644 --- a/eBook/examples/chapter_13/even/even/even.go +++ b/eBook/examples/chapter_13/even/even/even.go @@ -1,10 +1,10 @@ -// even.go -package even - -func Even(i int) bool { // Exported function - return i%2 == 0 -} - -func Odd(i int) bool { // Exported function - return i%2 != 0 -} +// even.go +package even + +func Even(i int) bool { // Exported function + return i%2 == 0 +} + +func Odd(i int) bool { // Exported function + return i%2 != 0 +} diff --git a/eBook/examples/chapter_13/even/even/oddeven_test.go b/eBook/examples/chapter_13/even/even/oddeven_test.go index 0afd978..24ef552 100644 --- a/eBook/examples/chapter_13/even/even/oddeven_test.go +++ b/eBook/examples/chapter_13/even/even/oddeven_test.go @@ -1,27 +1,27 @@ -// oddeven_test.go -package even - -import "testing" - -func TestEven(t *testing.T) { - if !Even(10) { - t.Log(" 10 must be even!") - t.Fail() - } - if Even(7) { - t.Log(" 7 is not even!") - t.Fail() - } - -} - -func TestOdd(t *testing.T) { - if !Odd(11) { - t.Log(" 11 must be odd!") - t.Fail() - } - if Odd(10) { - t.Log(" 10 is not odd!") - t.Fail() - } -} \ No newline at end of file +// oddeven_test.go +package even + +import "testing" + +func TestEven(t *testing.T) { + if !Even(10) { + t.Log(" 10 must be even!") + t.Fail() + } + if Even(7) { + t.Log(" 7 is not even!") + t.Fail() + } + +} + +func TestOdd(t *testing.T) { + if !Odd(11) { + t.Log(" 11 must be odd!") + t.Fail() + } + if Odd(10) { + t.Log(" 10 is not odd!") + t.Fail() + } +} diff --git a/eBook/examples/chapter_13/even/even_main/even_main.go b/eBook/examples/chapter_13/even/even_main/even_main.go index bf9dd88..e96f031 100644 --- a/eBook/examples/chapter_13/even/even_main/even_main.go +++ b/eBook/examples/chapter_13/even/even_main/even_main.go @@ -1,13 +1,13 @@ -// test_oddeven.go -package main - -import ( - "fmt" - "even/even" -) - -func main() { - for i:=0; i<=100; i++ { - fmt.Printf("Is the integer %d even? %v\n", i, even.Even(i)) - } -} +// test_oddeven.go +package main + +import ( + "even/even" + "fmt" +) + +func main() { + for i := 0; i <= 100; i++ { + fmt.Printf("Is the integer %d even? %v\n", i, even.Even(i)) + } +} diff --git a/eBook/examples/chapter_13/exec.go b/eBook/examples/chapter_13/exec.go index c81f6e1..0080a11 100644 --- a/eBook/examples/chapter_13/exec.go +++ b/eBook/examples/chapter_13/exec.go @@ -1,61 +1,61 @@ -// exec.go -package main -import ( - "fmt" - "os/exec" - "os" -) - -func main() { -// 1) os.StartProcess // -/*********************/ -/* Linux: */ - env := os.Environ() - procAttr := &os.ProcAttr{ - Env: env, - Files: []*os.File{ - os.Stdin, - os.Stdout, - os.Stderr, - }, - } - // 1st example: list files - pid, err := os.StartProcess("/bin/ls", []string{"ls", "-l"}, procAttr) - if err != nil { - fmt.Printf("Error %v starting process!", err) // - os.Exit(1) - } - fmt.Printf("The process id is %v", pid) - // 2nd example: show all processes - pid, err = os.StartProcess("/bin/ps", []string{"-e", "-opid,ppid,comm"}, procAttr) - if err != nil { - fmt.Printf("Error %v starting process!", err) // - os.Exit(1) - } - fmt.Printf("The process id is %v", pid) -/* Output 1st: -The process id is &{2054 0}total 2056 --rwxr-xr-x 1 ivo ivo 1157555 2011-07-04 16:48 Mieken_exec --rw-r--r-- 1 ivo ivo 2124 2011-07-04 16:48 Mieken_exec.go --rw-r--r-- 1 ivo ivo 18528 2011-07-04 16:48 Mieken_exec_go_.6 --rwxr-xr-x 1 ivo ivo 913920 2011-06-03 16:13 panic.exe --rw-r--r-- 1 ivo ivo 180 2011-04-11 20:39 panic.go -*/ - -// 2) exec.Run // -/***************/ -// Linux: OK, but not for ls ? -// cmd := exec.Command("ls", "-l") // no error, but doesn't show anything ? -// cmd := exec.Command("ls") // no error, but doesn't show anything ? - cmd := exec.Command("gedit") // this opens a gedit-window - err = cmd.Run() - if err != nil { - fmt.Printf("Error %v executing command!", err) - os.Exit(1) - } - fmt.Printf("The command is %v", cmd) -// The command is &{/bin/ls [ls -l] [] 0xf840000210 true [0xf84000ea50 0xf84000e9f0 0xf84000e9c0] [0xf84000ea50 0xf84000e9f0 0xf84000e9c0] [] [] 0xf8400128c0} -} -// in Windows: uitvoering: Error fork/exec /bin/ls: The system cannot find the path specified. starting process! - - +// exec.go +package main + +import ( + "fmt" + "os" + "os/exec" +) + +func main() { + // 1) os.StartProcess // + /*********************/ + /* Linux: */ + env := os.Environ() + procAttr := &os.ProcAttr{ + Env: env, + Files: []*os.File{ + os.Stdin, + os.Stdout, + os.Stderr, + }, + } + // 1st example: list files + pid, err := os.StartProcess("/bin/ls", []string{"ls", "-l"}, procAttr) + if err != nil { + fmt.Printf("Error %v starting process!", err) // + os.Exit(1) + } + fmt.Printf("The process id is %v", pid) + // 2nd example: show all processes + pid, err = os.StartProcess("/bin/ps", []string{"-e", "-opid,ppid,comm"}, procAttr) + if err != nil { + fmt.Printf("Error %v starting process!", err) // + os.Exit(1) + } + fmt.Printf("The process id is %v", pid) + /* Output 1st: + The process id is &{2054 0}total 2056 + -rwxr-xr-x 1 ivo ivo 1157555 2011-07-04 16:48 Mieken_exec + -rw-r--r-- 1 ivo ivo 2124 2011-07-04 16:48 Mieken_exec.go + -rw-r--r-- 1 ivo ivo 18528 2011-07-04 16:48 Mieken_exec_go_.6 + -rwxr-xr-x 1 ivo ivo 913920 2011-06-03 16:13 panic.exe + -rw-r--r-- 1 ivo ivo 180 2011-04-11 20:39 panic.go + */ + + // 2) exec.Run // + /***************/ + // Linux: OK, but not for ls ? + // cmd := exec.Command("ls", "-l") // no error, but doesn't show anything ? + // cmd := exec.Command("ls") // no error, but doesn't show anything ? + cmd := exec.Command("gedit") // this opens a gedit-window + err = cmd.Run() + if err != nil { + fmt.Printf("Error %v executing command!", err) + os.Exit(1) + } + fmt.Printf("The command is %v", cmd) + // The command is &{/bin/ls [ls -l] [] 0xf840000210 true [0xf84000ea50 0xf84000e9f0 0xf84000e9c0] [0xf84000ea50 0xf84000e9f0 0xf84000e9c0] [] [] 0xf8400128c0} +} + +// in Windows: uitvoering: Error fork/exec /bin/ls: The system cannot find the path specified. starting process! diff --git a/eBook/examples/chapter_13/panic.go b/eBook/examples/chapter_13/panic.go index 139c62f..04da6c8 100644 --- a/eBook/examples/chapter_13/panic.go +++ b/eBook/examples/chapter_13/panic.go @@ -1,9 +1,9 @@ -package main - -import "fmt" - -func main() { - fmt.Println("Starting the program") - panic("A severe error occurred: stopping the program!") - fmt.Println("Ending the program") -} \ No newline at end of file +package main + +import "fmt" + +func main() { + fmt.Println("Starting the program") + panic("A severe error occurred: stopping the program!") + fmt.Println("Ending the program") +} diff --git a/eBook/examples/chapter_13/panic_package.go b/eBook/examples/chapter_13/panic_package.go index 8368875..067fbb6 100644 --- a/eBook/examples/chapter_13/panic_package.go +++ b/eBook/examples/chapter_13/panic_package.go @@ -1,39 +1,40 @@ -// panic_package.go -package main - -import ( - "fmt" - "./parse/parse" -) - -func main() { - var examples = []string{ - "1 2 3 4 5", - "100 50 25 12.5 6.25", - "2 + 2 = 4", - "1st class", - "", - } - - for _, ex := range examples { - fmt.Printf("Parsing %q:\n ", ex) - nums, err := parse.Parse(ex) - if err != nil { - fmt.Println(err) // here String() method from ParseError is used - continue - } - fmt.Println(nums) - } -} -/* Output: -Parsing "1 2 3 4 5": - [1 2 3 4 5] -Parsing "100 50 25 12.5 6.25": - pkg parse: error parsing "12.5" as int -Parsing "2 + 2 = 4": - pkg parse: error parsing "+" as int -Parsing "1st class": - pkg parse: error parsing "1st" as int -Parsing "": - pkg: no words to parse -*/ +// panic_package.go +package main + +import ( + "./parse/parse" + "fmt" +) + +func main() { + var examples = []string{ + "1 2 3 4 5", + "100 50 25 12.5 6.25", + "2 + 2 = 4", + "1st class", + "", + } + + for _, ex := range examples { + fmt.Printf("Parsing %q:\n ", ex) + nums, err := parse.Parse(ex) + if err != nil { + fmt.Println(err) // here String() method from ParseError is used + continue + } + fmt.Println(nums) + } +} + +/* Output: +Parsing "1 2 3 4 5": + [1 2 3 4 5] +Parsing "100 50 25 12.5 6.25": + pkg parse: error parsing "12.5" as int +Parsing "2 + 2 = 4": + pkg parse: error parsing "+" as int +Parsing "1st class": + pkg parse: error parsing "1st" as int +Parsing "": + pkg: no words to parse +*/ diff --git a/eBook/examples/chapter_13/panic_recover.go b/eBook/examples/chapter_13/panic_recover.go index e743575..c785f65 100644 --- a/eBook/examples/chapter_13/panic_recover.go +++ b/eBook/examples/chapter_13/panic_recover.go @@ -1,32 +1,32 @@ -// panic_recover.go -package main - -import ( - "fmt" -) - -func badCall() { - panic("bad end") -} - -func test() { - defer func() { - if e := recover(); e != nil { - fmt.Printf("Panicing %s\r\n", e) - } - }() - badCall() - fmt.Printf("After bad call\r\n") // <-- wordt niet bereikt -} - -func main() { - fmt.Printf("Calling test\r\n") - test() - fmt.Printf("Test completed\r\n") -} - -/* Output: -Calling test -Panicing bad end -Test completed -*/ +// panic_recover.go +package main + +import ( + "fmt" +) + +func badCall() { + panic("bad end") +} + +func test() { + defer func() { + if e := recover(); e != nil { + fmt.Printf("Panicing %s\r\n", e) + } + }() + badCall() + fmt.Printf("After bad call\r\n") // <-- wordt niet bereikt +} + +func main() { + fmt.Printf("Calling test\r\n") + test() + fmt.Printf("Test completed\r\n") +} + +/* Output: +Calling test +Panicing bad end +Test completed +*/ diff --git a/eBook/examples/chapter_13/parse/parse.go b/eBook/examples/chapter_13/parse/parse.go index 1c81a3c..d82a8ba 100644 --- a/eBook/examples/chapter_13/parse/parse.go +++ b/eBook/examples/chapter_13/parse/parse.go @@ -1,51 +1,51 @@ -// parse.go -package parse - -import ( - "fmt" - "strings" - "strconv" -) - -// A ParseError indicates an error in converting a word into an integer. -type ParseError struct { - Index int // The index into the space-separated list of words. - Word string // The word that generated the parse error. - Err error // The raw error that precipitated this error, if any. -} - -// String returns a human-readable error message. -func (e *ParseError) String() string { - return fmt.Sprintf("pkg parse: error parsing %q as int", e.Word) -} - -// Parse parses the space-separated words in in put as integers. -func Parse(input string) (numbers []int, err error) { - defer func() { - if r := recover(); r != nil { - var ok bool - err, ok = r.(error) - if !ok { - err = fmt.Errorf("pkg: %v", r) - } - } - }() - - fields := strings.Fields(input) - numbers = fields2numbers(fields) - return -} - -func fields2numbers(fields []string) (numbers []int) { - if len(fields) == 0 { - panic("no words to parse") - } - for idx, field := range fields { - num, err := strconv.Atoi(field) - if err != nil { - panic(&ParseError{idx, field, err}) - } - numbers = append(numbers, num) - } - return -} +// parse.go +package parse + +import ( + "fmt" + "strconv" + "strings" +) + +// A ParseError indicates an error in converting a word into an integer. +type ParseError struct { + Index int // The index into the space-separated list of words. + Word string // The word that generated the parse error. + Err error // The raw error that precipitated this error, if any. +} + +// String returns a human-readable error message. +func (e *ParseError) String() string { + return fmt.Sprintf("pkg parse: error parsing %q as int", e.Word) +} + +// Parse parses the space-separated words in in put as integers. +func Parse(input string) (numbers []int, err error) { + defer func() { + if r := recover(); r != nil { + var ok bool + err, ok = r.(error) + if !ok { + err = fmt.Errorf("pkg: %v", r) + } + } + }() + + fields := strings.Fields(input) + numbers = fields2numbers(fields) + return +} + +func fields2numbers(fields []string) (numbers []int) { + if len(fields) == 0 { + panic("no words to parse") + } + for idx, field := range fields { + num, err := strconv.Atoi(field) + if err != nil { + panic(&ParseError{idx, field, err}) + } + numbers = append(numbers, num) + } + return +} diff --git a/eBook/examples/chapter_14/benchmark_channels.go b/eBook/examples/chapter_14/benchmark_channels.go index c05a7f5..0eb2a44 100644 --- a/eBook/examples/chapter_14/benchmark_channels.go +++ b/eBook/examples/chapter_14/benchmark_channels.go @@ -1,35 +1,35 @@ -package main - -import ( - "fmt" - "testing" -) - -func main() { - fmt.Println(" sync", testing.Benchmark(BenchmarkChannelSync).String()) - fmt.Println("buffered", testing.Benchmark(BenchmarkChannelBuffered).String()) -} - -func BenchmarkChannelSync(b *testing.B) { - ch := make(chan int) - go func() { - for i := 0; i < b.N; i++ { - ch <- i - } - close(ch) - }() - for _ = range ch { - } -} - -func BenchmarkChannelBuffered(b *testing.B) { - ch := make(chan int, 128) - go func() { - for i := 0; i < b.N; i++ { - ch <- i - } - close(ch) - }() - for _ = range ch { - } -} +package main + +import ( + "fmt" + "testing" +) + +func main() { + fmt.Println(" sync", testing.Benchmark(BenchmarkChannelSync).String()) + fmt.Println("buffered", testing.Benchmark(BenchmarkChannelBuffered).String()) +} + +func BenchmarkChannelSync(b *testing.B) { + ch := make(chan int) + go func() { + for i := 0; i < b.N; i++ { + ch <- i + } + close(ch) + }() + for range ch { + } +} + +func BenchmarkChannelBuffered(b *testing.B) { + ch := make(chan int, 128) + go func() { + for i := 0; i < b.N; i++ { + ch <- i + } + close(ch) + }() + for range ch { + } +} diff --git a/eBook/examples/chapter_14/chaining.go b/eBook/examples/chapter_14/chaining.go index 42d595e..2f25b13 100644 --- a/eBook/examples/chapter_14/chaining.go +++ b/eBook/examples/chapter_14/chaining.go @@ -7,7 +7,7 @@ import ( var ngoroutine = flag.Int("n", 100000, "how many goroutines") -func f(left, right chan int) { left <- 1+<-right } +func f(left, right chan int) { left <- 1 + <-right } func main() { flag.Parse() @@ -17,7 +17,7 @@ func main() { left, right = right, make(chan int) go f(left, right) } - right <- 0 // bang! - x := <-leftmost // wait for completion - fmt.Println(x) // 100000, ongeveer 1,5 s + right <- 0 // bang! + x := <-leftmost // wait for completion + fmt.Println(x) // 100000, ongeveer 1,5 s } diff --git a/eBook/examples/chapter_14/channel_block.go b/eBook/examples/chapter_14/channel_block.go index d45d041..510afcb 100644 --- a/eBook/examples/chapter_14/channel_block.go +++ b/eBook/examples/chapter_14/channel_block.go @@ -1,16 +1,15 @@ -package main - -import "fmt" - -func main() { - ch1 := make(chan int) - go pump(ch1) // pump hangs - fmt.Println(<-ch1) // prints only 0 -} - -func pump(ch chan int) { - for i := 0; ; i++ { - ch <- i - } -} - +package main + +import "fmt" + +func main() { + ch1 := make(chan int) + go pump(ch1) // pump hangs + fmt.Println(<-ch1) // prints only 0 +} + +func pump(ch chan int) { + for i := 0; ; i++ { + ch <- i + } +} diff --git a/eBook/examples/chapter_14/channel_block2.go b/eBook/examples/chapter_14/channel_block2.go index eae7239..cf4931c 100644 --- a/eBook/examples/chapter_14/channel_block2.go +++ b/eBook/examples/chapter_14/channel_block2.go @@ -1,25 +1,25 @@ -package main - -import ( - "fmt" - "time" -) - -func main() { - ch1 := make(chan int) - go pump(ch1) - go suck(ch1) // tons of numbers appear - time.Sleep(1e9) -} - -func pump(ch chan int) { - for i := 0; ; i++ { - ch <- i - } -} - -func suck(ch chan int) { - for { - fmt.Println(<-ch) - } -} +package main + +import ( + "fmt" + "time" +) + +func main() { + ch1 := make(chan int) + go pump(ch1) + go suck(ch1) // tons of numbers appear + time.Sleep(1e9) +} + +func pump(ch chan int) { + for i := 0; ; i++ { + ch <- i + } +} + +func suck(ch chan int) { + for { + fmt.Println(<-ch) + } +} diff --git a/eBook/examples/chapter_14/channel_idiom2.go b/eBook/examples/chapter_14/channel_idiom2.go index 1499008..7ac3a37 100644 --- a/eBook/examples/chapter_14/channel_idiom2.go +++ b/eBook/examples/chapter_14/channel_idiom2.go @@ -1,29 +1,29 @@ -package main - -import ( - "fmt" - "time" -) - -func main() { - suck(pump()) - time.Sleep(1e9) -} - -func pump() chan int { - ch := make(chan int) - go func() { - for i := 0; ; i++ { - ch <- i - } - }() - return ch -} - -func suck(ch chan int) { - go func() { - for v := range ch { - fmt.Println(v) - } - }() -} +package main + +import ( + "fmt" + "time" +) + +func main() { + suck(pump()) + time.Sleep(1e9) +} + +func pump() chan int { + ch := make(chan int) + go func() { + for i := 0; ; i++ { + ch <- i + } + }() + return ch +} + +func suck(ch chan int) { + go func() { + for v := range ch { + fmt.Println(v) + } + }() +} diff --git a/eBook/examples/chapter_14/conc_access.go b/eBook/examples/chapter_14/conc_access.go index 3bc20cc..8a2f15b 100644 --- a/eBook/examples/chapter_14/conc_access.go +++ b/eBook/examples/chapter_14/conc_access.go @@ -1,54 +1,55 @@ -// conc_access.go -package main - -import ( - "fmt" - "strconv" -) - -type Person struct { - Name string - salary float64 - chF chan func() -} - -func NewPerson(name string, salary float64) *Person { - p := &Person{name, salary, make(chan func())} - go p.backend() - return p -} - -func (p *Person) backend() { - for f := range p.chF { - f() - } -} - -// Set salary. -func (p *Person) SetSalary(sal float64) { - p.chF <- func() { p.salary = sal } -} - -// Retrieve salary. -func (p *Person) Salary() float64 { - fChan := make(chan float64) - p.chF <- func() { fChan <- p.salary } - return <-fChan -} - -func (p *Person) String() string { - return "Person - name is: " + p.Name + " - salary is: " + strconv.FormatFloat(p.Salary(), 'f', 2, 64) -} - -func main() { - bs := NewPerson("Smith Bill", 2500.5) - fmt.Println(bs) - bs.SetSalary(4000.25) - fmt.Println("Salary changed:") - fmt.Println(bs) -} -/* Output: -Person - name is: Smith Bill - salary is: 2500.50 -Salary changed: -Person - name is: Smith Bill - salary is: 4000.25 -*/ +// conc_access.go +package main + +import ( + "fmt" + "strconv" +) + +type Person struct { + Name string + salary float64 + chF chan func() +} + +func NewPerson(name string, salary float64) *Person { + p := &Person{name, salary, make(chan func())} + go p.backend() + return p +} + +func (p *Person) backend() { + for f := range p.chF { + f() + } +} + +// Set salary. +func (p *Person) SetSalary(sal float64) { + p.chF <- func() { p.salary = sal } +} + +// Retrieve salary. +func (p *Person) Salary() float64 { + fChan := make(chan float64) + p.chF <- func() { fChan <- p.salary } + return <-fChan +} + +func (p *Person) String() string { + return "Person - name is: " + p.Name + " - salary is: " + strconv.FormatFloat(p.Salary(), 'f', 2, 64) +} + +func main() { + bs := NewPerson("Smith Bill", 2500.5) + fmt.Println(bs) + bs.SetSalary(4000.25) + fmt.Println("Salary changed:") + fmt.Println(bs) +} + +/* Output: +Person - name is: Smith Bill - salary is: 2500.50 +Salary changed: +Person - name is: Smith Bill - salary is: 4000.25 +*/ diff --git a/eBook/examples/chapter_14/general_lazy_evalution1.go b/eBook/examples/chapter_14/general_lazy_evalution1.go index c645b63..1cfdde4 100644 --- a/eBook/examples/chapter_14/general_lazy_evalution1.go +++ b/eBook/examples/chapter_14/general_lazy_evalution1.go @@ -1,57 +1,58 @@ -package main - -import ( - "fmt" -) - -type Any interface{} -type EvalFunc func(Any) (Any, Any) - -func main() { - evenFunc := func(state Any) (Any, Any) { - os := state.(int) - ns := os + 2 - return os, ns - } - even := BuildLazyIntEvaluator(evenFunc, 0) - - for i := 0; i < 10; i++ { - fmt.Printf("%vth even: %v\n", i, even()) - } -} - -func BuildLazyEvaluator(evalFunc EvalFunc, initState Any) func() Any { - retValChan := make(chan Any) - loopFunc := func() { - var actState Any = initState - var retVal Any - for { - retVal, actState = evalFunc(actState) - retValChan <- retVal - } - } - retFunc := func() Any { - return <-retValChan - } - go loopFunc() - return retFunc -} - -func BuildLazyIntEvaluator(evalFunc EvalFunc, initState Any) func() int { - ef := BuildLazyEvaluator(evalFunc, initState) - return func() int { - return ef().(int) - } -} -/* Output: -0th even: 0 -1th even: 2 -2th even: 4 -3th even: 6 -4th even: 8 -5th even: 10 -6th even: 12 -7th even: 14 -8th even: 16 -9th even: 18 -*/ +package main + +import ( + "fmt" +) + +type Any interface{} +type EvalFunc func(Any) (Any, Any) + +func main() { + evenFunc := func(state Any) (Any, Any) { + os := state.(int) + ns := os + 2 + return os, ns + } + even := BuildLazyIntEvaluator(evenFunc, 0) + + for i := 0; i < 10; i++ { + fmt.Printf("%vth even: %v\n", i, even()) + } +} + +func BuildLazyEvaluator(evalFunc EvalFunc, initState Any) func() Any { + retValChan := make(chan Any) + loopFunc := func() { + var actState Any = initState + var retVal Any + for { + retVal, actState = evalFunc(actState) + retValChan <- retVal + } + } + retFunc := func() Any { + return <-retValChan + } + go loopFunc() + return retFunc +} + +func BuildLazyIntEvaluator(evalFunc EvalFunc, initState Any) func() int { + ef := BuildLazyEvaluator(evalFunc, initState) + return func() int { + return ef().(int) + } +} + +/* Output: +0th even: 0 +1th even: 2 +2th even: 4 +3th even: 6 +4th even: 8 +5th even: 10 +6th even: 12 +7th even: 14 +8th even: 16 +9th even: 18 +*/ diff --git a/eBook/examples/chapter_14/goroutine1.go b/eBook/examples/chapter_14/goroutine1.go index df3eba5..574b79c 100644 --- a/eBook/examples/chapter_14/goroutine1.go +++ b/eBook/examples/chapter_14/goroutine1.go @@ -1,29 +1,29 @@ -package main - -import ( - "fmt" - "time" -) - -func main() { - fmt.Println("In main()") - // longWait() - go longWait() - // shortWait() - go shortWait() - fmt.Println("About to sleep in main()") - time.Sleep(10 * 1e9) // sleep works with a Duration in nanoseconds (ns) ! - fmt.Println("At the end of main()") -} - -func longWait() { - fmt.Println("Beginning longWait()") - time.Sleep(5 * 1e9) // sleep for 5 seconds - fmt.Println("End of longWait()") -} - -func shortWait() { - fmt.Println("Beginning shortWait()") - time.Sleep(2 * 1e9) // sleep for 2 seconds - fmt.Println("End of shortWait()") -} +package main + +import ( + "fmt" + "time" +) + +func main() { + fmt.Println("In main()") + // longWait() + go longWait() + // shortWait() + go shortWait() + fmt.Println("About to sleep in main()") + time.Sleep(10 * 1e9) // sleep works with a Duration in nanoseconds (ns) ! + fmt.Println("At the end of main()") +} + +func longWait() { + fmt.Println("Beginning longWait()") + time.Sleep(5 * 1e9) // sleep for 5 seconds + fmt.Println("End of longWait()") +} + +func shortWait() { + fmt.Println("Beginning shortWait()") + time.Sleep(2 * 1e9) // sleep for 2 seconds + fmt.Println("End of shortWait()") +} diff --git a/eBook/examples/chapter_14/goroutine2.go b/eBook/examples/chapter_14/goroutine2.go index f504f8c..bb0460d 100644 --- a/eBook/examples/chapter_14/goroutine2.go +++ b/eBook/examples/chapter_14/goroutine2.go @@ -1,33 +1,34 @@ -package main - -import ( - "fmt" - "time" -) - -func main() { - ch := make(chan string) - - go sendData(ch) - go getData(ch) - - time.Sleep(1e9) -} - -func sendData(ch chan string) { - ch <- "Washington" - ch <- "Tripoli" - ch <- "London" - ch <- "Beijing" - ch <- "Tokio" -} - -func getData(ch chan string) { - var input string - // time.Sleep(1e9) - for { - input = <-ch - fmt.Printf("%s ", input) - } -} -// Washington Tripoli London Beijing Tokio \ No newline at end of file +package main + +import ( + "fmt" + "time" +) + +func main() { + ch := make(chan string) + + go sendData(ch) + go getData(ch) + + time.Sleep(1e9) +} + +func sendData(ch chan string) { + ch <- "Washington" + ch <- "Tripoli" + ch <- "London" + ch <- "Beijing" + ch <- "Tokio" +} + +func getData(ch chan string) { + var input string + // time.Sleep(1e9) + for { + input = <-ch + fmt.Printf("%s ", input) + } +} + +// Washington Tripoli London Beijing Tokio diff --git a/eBook/examples/chapter_14/goroutine3.go b/eBook/examples/chapter_14/goroutine3.go index f827593..8fd16c5 100644 --- a/eBook/examples/chapter_14/goroutine3.go +++ b/eBook/examples/chapter_14/goroutine3.go @@ -1,29 +1,30 @@ -package main - -import "fmt" - -func main() { - ch := make(chan string) - go sendData(ch) - getData(ch) -} - -func sendData(ch chan string) { - ch <- "Washington" - ch <- "Tripoli" - ch <- "London" - ch <- "Beijing" - ch <- "Tokio" - close(ch) -} - -func getData(ch chan string) { - for { - input, open := <-ch - if !open { - break - } - fmt.Printf("%s ", input) - } -} -// Washington Tripoli London Beijing Tokio \ No newline at end of file +package main + +import "fmt" + +func main() { + ch := make(chan string) + go sendData(ch) + getData(ch) +} + +func sendData(ch chan string) { + ch <- "Washington" + ch <- "Tripoli" + ch <- "London" + ch <- "Beijing" + ch <- "Tokio" + close(ch) +} + +func getData(ch chan string) { + for { + input, open := <-ch + if !open { + break + } + fmt.Printf("%s ", input) + } +} + +// Washington Tripoli London Beijing Tokio diff --git a/eBook/examples/chapter_14/goroutine_select.go b/eBook/examples/chapter_14/goroutine_select.go index b88877f..55d5c10 100644 --- a/eBook/examples/chapter_14/goroutine_select.go +++ b/eBook/examples/chapter_14/goroutine_select.go @@ -1,40 +1,40 @@ -package main - -import ( - "fmt" - "time" -) - -func main() { - ch1 := make(chan int) - ch2 := make(chan int) - - go pump1(ch1) - go pump2(ch2) - go suck(ch1, ch2) - - time.Sleep(1e9) -} - -func pump1(ch chan int) { - for i := 0; ; i++ { - ch <- i * 2 - } -} - -func pump2(ch chan int) { - for i := 0; ; i++ { - ch <- i + 5 - } -} - -func suck(ch1, ch2 chan int) { - for { - select { - case v := <-ch1: - fmt.Printf("Received on channel 1: %d\n", v) - case v := <-ch2: - fmt.Printf("Received on channel 2: %d\n", v) - } - } -} +package main + +import ( + "fmt" + "time" +) + +func main() { + ch1 := make(chan int) + ch2 := make(chan int) + + go pump1(ch1) + go pump2(ch2) + go suck(ch1, ch2) + + time.Sleep(1e9) +} + +func pump1(ch chan int) { + for i := 0; ; i++ { + ch <- i * 2 + } +} + +func pump2(ch chan int) { + for i := 0; ; i++ { + ch <- i + 5 + } +} + +func suck(ch1, ch2 chan int) { + for { + select { + case v := <-ch1: + fmt.Printf("Received on channel 1: %d\n", v) + case v := <-ch2: + fmt.Printf("Received on channel 2: %d\n", v) + } + } +} diff --git a/eBook/examples/chapter_14/goroutine_select2.go b/eBook/examples/chapter_14/goroutine_select2.go index 8adb7c2..318a0a1 100644 --- a/eBook/examples/chapter_14/goroutine_select2.go +++ b/eBook/examples/chapter_14/goroutine_select2.go @@ -1,49 +1,47 @@ -package main - -import ( - "fmt" - "time" - "runtime" -) - -func main() { - // setting GOMAXPROCS to 2 gives +- 22% performance increase, - // but increasing the number doesn't increase the performance - // without GOMAXPROCS: +- 86000 - // setting GOMAXPROCS to 2: +- 105000 - // setting GOMAXPROCS to 3: +- 94000 - runtime.GOMAXPROCS(2) - ch1 := make(chan int) - ch2 := make(chan int) - - go pump1(ch1) - go pump2(ch2) - go suck(ch1, ch2) - - time.Sleep(1e9) -} - -func pump1(ch chan int) { - for i:=0; ; i++ { - ch <- i*2 - } -} - -func pump2(ch chan int) { - for i:=0; ; i++ { - ch <- i+5 - } -} - -func suck(ch1,ch2 chan int) { - for i := 0; ; i++ { - select { - case v := <- ch1: - fmt.Printf("%d - Received on channel 1: %d\n", i, v) - case v := <- ch2: - fmt.Printf("%d - Received on channel 2: %d\n", i, v) - } - } -} - - +package main + +import ( + "fmt" + "runtime" + "time" +) + +func main() { + // setting GOMAXPROCS to 2 gives +- 22% performance increase, + // but increasing the number doesn't increase the performance + // without GOMAXPROCS: +- 86000 + // setting GOMAXPROCS to 2: +- 105000 + // setting GOMAXPROCS to 3: +- 94000 + runtime.GOMAXPROCS(2) + ch1 := make(chan int) + ch2 := make(chan int) + + go pump1(ch1) + go pump2(ch2) + go suck(ch1, ch2) + + time.Sleep(1e9) +} + +func pump1(ch chan int) { + for i := 0; ; i++ { + ch <- i * 2 + } +} + +func pump2(ch chan int) { + for i := 0; ; i++ { + ch <- i + 5 + } +} + +func suck(ch1, ch2 chan int) { + for i := 0; ; i++ { + select { + case v := <-ch1: + fmt.Printf("%d - Received on channel 1: %d\n", i, v) + case v := <-ch2: + fmt.Printf("%d - Received on channel 2: %d\n", i, v) + } + } +} diff --git a/eBook/examples/chapter_14/lazy_evaluation.go b/eBook/examples/chapter_14/lazy_evaluation.go index f2e2348..5058255 100644 --- a/eBook/examples/chapter_14/lazy_evaluation.go +++ b/eBook/examples/chapter_14/lazy_evaluation.go @@ -1,30 +1,30 @@ -// lazy_evaluation.go -package main - -import ( - "fmt" -) - -var resume chan int - -func integers() chan int { - yield := make (chan int) - count := 0 - go func () { - for { - yield <- count - count++ - } - } () - return yield -} - -func generateInteger() int { - return <-resume -} -func main() { - resume = integers() - fmt.Println(generateInteger()) //=> 0 - fmt.Println(generateInteger()) //=> 1 - fmt.Println(generateInteger()) //=> 2 -} +// lazy_evaluation.go +package main + +import ( + "fmt" +) + +var resume chan int + +func integers() chan int { + yield := make(chan int) + count := 0 + go func() { + for { + yield <- count + count++ + } + }() + return yield +} + +func generateInteger() int { + return <-resume +} +func main() { + resume = integers() + fmt.Println(generateInteger()) //=> 0 + fmt.Println(generateInteger()) //=> 1 + fmt.Println(generateInteger()) //=> 2 +} diff --git a/eBook/examples/chapter_14/max_tasks.go b/eBook/examples/chapter_14/max_tasks.go index 6965b32..8bcebff 100644 --- a/eBook/examples/chapter_14/max_tasks.go +++ b/eBook/examples/chapter_14/max_tasks.go @@ -1,31 +1,32 @@ -package main - -const MAXREQS = 50 -var sem = make(chan int, MAXREQS) - -type Request struct { - a, b int - replyc chan int -} - -func process(r *Request) { - // do something -} - -func handle(r *Request) { - sem <- 1 // doesn't matter what we put in it - process(r) - <-sem // one empty place in the buffer: the next request can start -} - -func server(service chan *Request) { - for { - request := <-service - go handle(request) - } -} - -func main() { - service := make(chan *Request) - go server(service) -} +package main + +const MAXREQS = 50 + +var sem = make(chan int, MAXREQS) + +type Request struct { + a, b int + replyc chan int +} + +func process(r *Request) { + // do something +} + +func handle(r *Request) { + sem <- 1 // doesn't matter what we put in it + process(r) + <-sem // one empty place in the buffer: the next request can start +} + +func server(service chan *Request) { + for { + request := <-service + go handle(request) + } +} + +func main() { + service := make(chan *Request) + go server(service) +} diff --git a/eBook/examples/chapter_14/multiplex_server.go b/eBook/examples/chapter_14/multiplex_server.go index 86e0b37..b6c09ff 100644 --- a/eBook/examples/chapter_14/multiplex_server.go +++ b/eBook/examples/chapter_14/multiplex_server.go @@ -1,53 +1,53 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -package main - -import "fmt" - -type Request struct { - a, b int - replyc chan int // reply channel inside the Request -} - -type binOp func(a, b int) int - -func run(op binOp, req *Request) { - req.replyc <- op(req.a, req.b) -} - -func server(op binOp, service chan *Request) { - for { - req := <-service // requests arrive here - // start goroutine for request: - go run(op, req) // don't wait for op - } -} - -func startServer(op binOp) chan *Request { - reqChan := make(chan *Request) - go server(op, reqChan) - return reqChan -} - -func main() { - adder := startServer(func(a, b int) int { return a + b }) - const N = 100 - var reqs [N]Request - for i := 0; i < N; i++ { - req := &reqs[i] - req.a = i - req.b = i + N - req.replyc = make(chan int) - adder <- req - } - // checks: - for i := N - 1; i >= 0; i-- { // doesn't matter what order - if <-reqs[i].replyc != N+2*i { - fmt.Println("fail at", i) - } else { - fmt.Println("Request ", i, " is ok!") - } - } - fmt.Println("done") -} +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +package main + +import "fmt" + +type Request struct { + a, b int + replyc chan int // reply channel inside the Request +} + +type binOp func(a, b int) int + +func run(op binOp, req *Request) { + req.replyc <- op(req.a, req.b) +} + +func server(op binOp, service chan *Request) { + for { + req := <-service // requests arrive here + // start goroutine for request: + go run(op, req) // don't wait for op + } +} + +func startServer(op binOp) chan *Request { + reqChan := make(chan *Request) + go server(op, reqChan) + return reqChan +} + +func main() { + adder := startServer(func(a, b int) int { return a + b }) + const N = 100 + var reqs [N]Request + for i := 0; i < N; i++ { + req := &reqs[i] + req.a = i + req.b = i + N + req.replyc = make(chan int) + adder <- req + } + // checks: + for i := N - 1; i >= 0; i-- { // doesn't matter what order + if <-reqs[i].replyc != N+2*i { + fmt.Println("fail at", i) + } else { + fmt.Println("Request ", i, " is ok!") + } + } + fmt.Println("done") +} diff --git a/eBook/examples/chapter_14/multiplex_server2.go b/eBook/examples/chapter_14/multiplex_server2.go index 49c0823..7749b58 100644 --- a/eBook/examples/chapter_14/multiplex_server2.go +++ b/eBook/examples/chapter_14/multiplex_server2.go @@ -1,58 +1,58 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -package main - -import "fmt" - -type Request struct { - a, b int - replyc chan int // reply channel inside the Request -} - -type binOp func(a, b int) int - -func run(op binOp, req *Request) { - req.replyc <- op(req.a, req.b) -} - -func server(op binOp, service chan *Request, quit chan bool) { - for { - select { - case req := <-service: - go run(op, req) - case <-quit: - return - } - } -} - -func startServer(op binOp) (service chan *Request, quit chan bool) { - service = make(chan *Request) - quit = make(chan bool) - go server(op, service, quit) - return service, quit -} - -func main() { - adder, quit := startServer(func(a, b int) int { return a + b }) - const N = 100 - var reqs [N]Request - for i := 0; i < N; i++ { - req := &reqs[i] - req.a = i - req.b = i + N - req.replyc = make(chan int) - adder <- req - } - // checks: - for i := N - 1; i >= 0; i-- { // doesn't matter what order - if <-reqs[i].replyc != N+2*i { - fmt.Println("fail at", i) - } else { - fmt.Println("Request ", i, " is ok!") - } - } - quit <- true - fmt.Println("done") -} +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +package main + +import "fmt" + +type Request struct { + a, b int + replyc chan int // reply channel inside the Request +} + +type binOp func(a, b int) int + +func run(op binOp, req *Request) { + req.replyc <- op(req.a, req.b) +} + +func server(op binOp, service chan *Request, quit chan bool) { + for { + select { + case req := <-service: + go run(op, req) + case <-quit: + return + } + } +} + +func startServer(op binOp) (service chan *Request, quit chan bool) { + service = make(chan *Request) + quit = make(chan bool) + go server(op, service, quit) + return service, quit +} + +func main() { + adder, quit := startServer(func(a, b int) int { return a + b }) + const N = 100 + var reqs [N]Request + for i := 0; i < N; i++ { + req := &reqs[i] + req.a = i + req.b = i + N + req.replyc = make(chan int) + adder <- req + } + // checks: + for i := N - 1; i >= 0; i-- { // doesn't matter what order + if <-reqs[i].replyc != N+2*i { + fmt.Println("fail at", i) + } else { + fmt.Println("Request ", i, " is ok!") + } + } + quit <- true + fmt.Println("done") +} diff --git a/eBook/examples/chapter_14/sieve1.go b/eBook/examples/chapter_14/sieve1.go index 184c76e..862f93e 100644 --- a/eBook/examples/chapter_14/sieve1.go +++ b/eBook/examples/chapter_14/sieve1.go @@ -1,37 +1,37 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file.package main -package main - -import "fmt" - -// Send the sequence 2, 3, 4, ... to channel 'ch'. -func generate(ch chan int) { - for i := 2; ; i++ { - ch <- i // Send 'i' to channel 'ch'. - } -} - -// Copy the values from channel 'in' to channel 'out', -// removing those divisible by 'prime'. -func filter(in, out chan int, prime int) { - for { - i := <-in // Receive value of new variable 'i' from 'in'. - if i%prime != 0 { - out <- i // Send 'i' to channel 'out'. - } - } -} - -// The prime sieve: Daisy-chain filter processes together. -func main() { - ch := make(chan int) // Create a new channel. - go generate(ch) // Start generate() as a goroutine. - for { - prime := <-ch - fmt.Print(prime, " ") - ch1 := make(chan int) - go filter(ch, ch1, prime) - ch = ch1 - } -} +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file.package main +package main + +import "fmt" + +// Send the sequence 2, 3, 4, ... to channel 'ch'. +func generate(ch chan int) { + for i := 2; ; i++ { + ch <- i // Send 'i' to channel 'ch'. + } +} + +// Copy the values from channel 'in' to channel 'out', +// removing those divisible by 'prime'. +func filter(in, out chan int, prime int) { + for { + i := <-in // Receive value of new variable 'i' from 'in'. + if i%prime != 0 { + out <- i // Send 'i' to channel 'out'. + } + } +} + +// The prime sieve: Daisy-chain filter processes together. +func main() { + ch := make(chan int) // Create a new channel. + go generate(ch) // Start generate() as a goroutine. + for { + prime := <-ch + fmt.Print(prime, " ") + ch1 := make(chan int) + go filter(ch, ch1, prime) + ch = ch1 + } +} diff --git a/eBook/examples/chapter_14/sieve2.go b/eBook/examples/chapter_14/sieve2.go index c3e4299..3614e59 100644 --- a/eBook/examples/chapter_14/sieve2.go +++ b/eBook/examples/chapter_14/sieve2.go @@ -1,53 +1,53 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "fmt" -) - -// Send the sequence 2, 3, 4, ... to returned channel -func generate() chan int { - ch := make(chan int) - go func() { - for i := 2; ; i++ { - ch <- i - } - }() - return ch -} - -// Filter out input values divisible by 'prime', send rest to returned channel -func filter(in chan int, prime int) chan int { - out := make(chan int) - go func() { - for { - if i := <-in; i%prime != 0 { - out <- i - } - } - }() - return out -} - -func sieve() chan int { - out := make(chan int) - go func() { - ch := generate() - for { - prime := <-ch - ch = filter(ch, prime) - out <- prime - } - }() - return out -} - -func main() { - primes := sieve() - for { - fmt.Println(<-primes) - } -} +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" +) + +// Send the sequence 2, 3, 4, ... to returned channel +func generate() chan int { + ch := make(chan int) + go func() { + for i := 2; ; i++ { + ch <- i + } + }() + return ch +} + +// Filter out input values divisible by 'prime', send rest to returned channel +func filter(in chan int, prime int) chan int { + out := make(chan int) + go func() { + for { + if i := <-in; i%prime != 0 { + out <- i + } + } + }() + return out +} + +func sieve() chan int { + out := make(chan int) + go func() { + ch := generate() + for { + prime := <-ch + ch = filter(ch, prime) + out <- prime + } + }() + return out +} + +func main() { + primes := sieve() + for { + fmt.Println(<-primes) + } +} diff --git a/eBook/examples/chapter_14/timer_goroutine.go b/eBook/examples/chapter_14/timer_goroutine.go index d9bfb5a..f1fdbe8 100644 --- a/eBook/examples/chapter_14/timer_goroutine.go +++ b/eBook/examples/chapter_14/timer_goroutine.go @@ -1,42 +1,43 @@ -// default.go -package main - -import ( - "fmt" - "time" -) - -func main() { - tick := time.Tick(1e8) - boom := time.After(5e8) - for { - select { - case <-tick: - fmt.Println("tick.") - case <-boom: - fmt.Println("BOOM!") - return - default: - fmt.Println(" .") - time.Sleep(5e7) - } - } -} -/* Output: - . - . -tick. - . - . -tick. - . - . -tick. - . - . -tick. - . - . -tick. -BOOM! -*/ +// default.go +package main + +import ( + "fmt" + "time" +) + +func main() { + tick := time.Tick(1e8) + boom := time.After(5e8) + for { + select { + case <-tick: + fmt.Println("tick.") + case <-boom: + fmt.Println("BOOM!") + return + default: + fmt.Println(" .") + time.Sleep(5e7) + } + } +} + +/* Output: + . + . +tick. + . + . +tick. + . + . +tick. + . + . +tick. + . + . +tick. +BOOM! +*/ diff --git a/eBook/examples/chapter_16/closures_goroutines.go b/eBook/examples/chapter_16/closures_goroutines.go index 7c2fdbe..e97826e 100644 --- a/eBook/examples/chapter_16/closures_goroutines.go +++ b/eBook/examples/chapter_16/closures_goroutines.go @@ -1,47 +1,48 @@ -// closures_goroutines.go -package main - -import ( - "fmt" - "time" -) - -var values = [5]int{10, 11, 12, 13, 14} - -func main() { - // version A: - for ix := range values { // ix is index! - func() { - fmt.Print(ix, " ") - }() // call closure, prints each index - } - fmt.Println() - // version B: same as A, but call closure as a goroutine - for ix := range values { - go func() { - fmt.Print(ix, " ") - }() - } - time.Sleep(1e9) - // version C: the right way - for ix := range values { - go func(ix interface{}) { - fmt.Print(ix, " ") - }(ix) - } - time.Sleep(1e9) - // version D: print out the values: - for ix := range values { - val := values[ix] - go func() { - fmt.Print(val, " ") - }() - } - time.Sleep(1e9) -} -/* Output: -0 1 2 3 4 -4 4 4 4 4 -1 0 3 4 2 -0 1 2 4 3 -*/ +// closures_goroutines.go +package main + +import ( + "fmt" + "time" +) + +var values = [5]int{10, 11, 12, 13, 14} + +func main() { + // version A: + for ix := range values { // ix is index! + func() { + fmt.Print(ix, " ") + }() // call closure, prints each index + } + fmt.Println() + // version B: same as A, but call closure as a goroutine + for ix := range values { + go func() { + fmt.Print(ix, " ") + }() + } + time.Sleep(1e9) + // version C: the right way + for ix := range values { + go func(ix interface{}) { + fmt.Print(ix, " ") + }(ix) + } + time.Sleep(1e9) + // version D: print out the values: + for ix := range values { + val := values[ix] + go func() { + fmt.Print(val, " ") + }() + } + time.Sleep(1e9) +} + +/* Output: +0 1 2 3 4 +4 4 4 4 4 +1 0 3 4 2 +0 1 2 4 3 +*/ diff --git a/eBook/examples/chapter_16/pointer_interface.go b/eBook/examples/chapter_16/pointer_interface.go index 18858b4..f0ad038 100644 --- a/eBook/examples/chapter_16/pointer_interface.go +++ b/eBook/examples/chapter_16/pointer_interface.go @@ -1,31 +1,30 @@ -// nexter.go -package main - -import ( - "fmt" -) - -type nexter interface { - next() byte -} - - -func nextFew1(n nexter, num int) []byte { - var b []byte - for i:=0; i < num; i++ { - b[i] = n.next() - } - return b -} - -func nextFew2(n *nexter, num int) []byte { - var b []byte - for i:=0; i < num; i++ { - b[i] = n.next() // compile error: n.next undefined (type *nexter has no field or method next) - } - return b -} - -func main() { - fmt.Println("Hello World!") -} +// nexter.go +package main + +import ( + "fmt" +) + +type nexter interface { + next() byte +} + +func nextFew1(n nexter, num int) []byte { + var b []byte + for i := 0; i < num; i++ { + b[i] = n.next() + } + return b +} + +func nextFew2(n *nexter, num int) []byte { + var b []byte + for i := 0; i < num; i++ { + b[i] = n.next() // compile error: n.next undefined (type *nexter has no field or method next) + } + return b +} + +func main() { + fmt.Println("Hello World!") +} diff --git a/eBook/examples/chapter_19/goto_v1/main.go b/eBook/examples/chapter_19/goto_v1/main.go index bcac800..4666585 100644 --- a/eBook/examples/chapter_19/goto_v1/main.go +++ b/eBook/examples/chapter_19/goto_v1/main.go @@ -11,6 +11,7 @@ URL: ` + var store = NewURLStore() func main() { @@ -29,7 +30,6 @@ func Redirect(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, url, http.StatusFound) } - func Add(w http.ResponseWriter, r *http.Request) { url := r.FormValue("url") if url == "" { diff --git a/eBook/examples/chapter_19/goto_v1/store.go b/eBook/examples/chapter_19/goto_v1/store.go index 1d6e598..7d65fc8 100644 --- a/eBook/examples/chapter_19/goto_v1/store.go +++ b/eBook/examples/chapter_19/goto_v1/store.go @@ -3,8 +3,8 @@ package main import "sync" type URLStore struct { - urls map[string]string - mu sync.RWMutex + urls map[string]string + mu sync.RWMutex } func NewURLStore() *URLStore { diff --git a/eBook/examples/chapter_19/goto_v2/main.go b/eBook/examples/chapter_19/goto_v2/main.go index 4849910..cecdbc9 100644 --- a/eBook/examples/chapter_19/goto_v2/main.go +++ b/eBook/examples/chapter_19/goto_v2/main.go @@ -23,7 +23,6 @@ func Redirect(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, url, http.StatusFound) } - func Add(w http.ResponseWriter, r *http.Request) { url := r.FormValue("url") if url == "" { diff --git a/eBook/examples/chapter_19/goto_v2/store.go b/eBook/examples/chapter_19/goto_v2/store.go index 0de2fd1..17e763a 100644 --- a/eBook/examples/chapter_19/goto_v2/store.go +++ b/eBook/examples/chapter_19/goto_v2/store.go @@ -9,9 +9,9 @@ import ( ) type URLStore struct { - urls map[string]string - mu sync.RWMutex - file *os.File + urls map[string]string + mu sync.RWMutex + file *os.File } type record struct { @@ -70,7 +70,7 @@ func (s *URLStore) load() error { if _, err := s.file.Seek(0, 0); err != nil { return err } - d := gob.NewDecoder(s.file) + d := gob.NewDecoder(s.file) var err error for err == nil { var r record diff --git a/eBook/examples/chapter_19/goto_v3/store.go b/eBook/examples/chapter_19/goto_v3/store.go index bb55289..b34e409 100644 --- a/eBook/examples/chapter_19/goto_v3/store.go +++ b/eBook/examples/chapter_19/goto_v3/store.go @@ -1,7 +1,7 @@ package main import ( -// "bufio" + // "bufio" "encoding/gob" "io" "log" @@ -12,9 +12,9 @@ import ( const saveQueueLength = 1000 type URLStore struct { - urls map[string]string - mu sync.RWMutex - save chan record + urls map[string]string + mu sync.RWMutex + save chan record } type record struct { @@ -74,9 +74,9 @@ func (s *URLStore) load(filename string) error { } defer f.Close() // buffered reading: - // b := bufio.NewReader(f) - // d := gob.NewDecoder(b) - d := gob.NewDecoder(f) + // b := bufio.NewReader(f) + // d := gob.NewDecoder(b) + d := gob.NewDecoder(f) for err == nil { var r record if err = d.Decode(&r); err == nil { @@ -97,13 +97,13 @@ func (s *URLStore) saveLoop(filename string) { log.Fatal("Error opening URLStore: ", err) } defer f.Close() - e := gob.NewEncoder(f) + e := gob.NewEncoder(f) // buffered encoding: - // b := bufio.NewWriter(f) + // b := bufio.NewWriter(f) // e := gob.NewEncoder(b) // defer b.Flush() for { - r := <-s.save // takes a record from the channel + r := <-s.save // takes a record from the channel if err := e.Encode(r); err != nil { log.Println("Error saving to URLStore: ", err) } diff --git a/eBook/examples/chapter_19/goto_v4/store.go b/eBook/examples/chapter_19/goto_v4/store.go index 54d5421..ca3c074 100644 --- a/eBook/examples/chapter_19/goto_v4/store.go +++ b/eBook/examples/chapter_19/goto_v4/store.go @@ -11,9 +11,9 @@ import ( const saveQueueLength = 1000 type URLStore struct { - urls map[string]string - mu sync.RWMutex - save chan record + urls map[string]string + mu sync.RWMutex + save chan record } type record struct { @@ -72,7 +72,7 @@ func (s *URLStore) load(filename string) error { return err } defer f.Close() - d := json.NewDecoder(f) + d := json.NewDecoder(f) for err == nil { var r record if err = d.Decode(&r); err == nil { @@ -93,9 +93,9 @@ func (s *URLStore) saveLoop(filename string) { log.Fatal("Error opening URLStore: ", err) } defer f.Close() - e := json.NewEncoder(f) + e := json.NewEncoder(f) for { - r := <-s.save // takes a record from the channel + r := <-s.save // takes a record from the channel if err := e.Encode(r); err != nil { log.Println("Error saving to URLStore: ", err) } diff --git a/eBook/examples/chapter_19/goto_v5/main.go b/eBook/examples/chapter_19/goto_v5/main.go index c054498..110266c 100644 --- a/eBook/examples/chapter_19/goto_v5/main.go +++ b/eBook/examples/chapter_19/goto_v5/main.go @@ -36,7 +36,7 @@ func main() { func Redirect(w http.ResponseWriter, r *http.Request) { key := r.URL.Path[1:] - if key == "" { + if key == "" { http.NotFound(w, r) return } diff --git a/eBook/examples/chapter_19/goto_v5/store.go b/eBook/examples/chapter_19/goto_v5/store.go index 557799f..9ceb337 100644 --- a/eBook/examples/chapter_19/goto_v5/store.go +++ b/eBook/examples/chapter_19/goto_v5/store.go @@ -5,8 +5,8 @@ import ( "errors" "io" "log" - "os" "net/rpc" + "os" "sync" ) @@ -18,14 +18,14 @@ type Store interface { } type ProxyStore struct { - urls *URLStore // local cache + urls *URLStore // local cache client *rpc.Client } type URLStore struct { - urls map[string]string - mu sync.RWMutex - save chan record + urls map[string]string + mu sync.RWMutex + save chan record } type record struct { diff --git a/eBook/examples/chapter_2/hello_world1.go b/eBook/examples/chapter_2/hello_world1.go index 0c71f1b..7ff097a 100644 --- a/eBook/examples/chapter_2/hello_world1.go +++ b/eBook/examples/chapter_2/hello_world1.go @@ -1,7 +1,6 @@ -// hello_world1.go -package main - -func main() { - println("Hello", "world") -} - +// hello_world1.go +package main + +func main() { + println("Hello", "world") +} diff --git a/eBook/examples/chapter_2/version.go b/eBook/examples/chapter_2/version.go index b470bbf..c7dd339 100644 --- a/eBook/examples/chapter_2/version.go +++ b/eBook/examples/chapter_2/version.go @@ -1,12 +1,13 @@ -package main - -import ( - "fmt" - "runtime" -) - -func main() { - fmt.Printf("%s", runtime.Version()) -} -// Output: -// go1.0.3 or go 1.1 +package main + +import ( + "fmt" + "runtime" +) + +func main() { + fmt.Printf("%s", runtime.Version()) +} + +// Output: +// go1.0.3 or go 1.1 diff --git a/eBook/examples/chapter_20/helloapp/hello/helloworld2_version1.go b/eBook/examples/chapter_20/helloapp/hello/helloworld2_version1.go index 66d664d..8987ced 100644 --- a/eBook/examples/chapter_20/helloapp/hello/helloworld2_version1.go +++ b/eBook/examples/chapter_20/helloapp/hello/helloworld2_version1.go @@ -1,14 +1,14 @@ -package hello - -import ( - "fmt" - "net/http" -) - -func init() { - http.HandleFunc("/", handler) -} - -func handler(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, "Hello, world!") -} +package hello + +import ( + "fmt" + "net/http" +) + +func init() { + http.HandleFunc("/", handler) +} + +func handler(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "Hello, world!") +} diff --git a/eBook/examples/chapter_20/helloapp/hello/helloworld2_version2.go b/eBook/examples/chapter_20/helloapp/hello/helloworld2_version2.go index 848a534..20c82fc 100644 --- a/eBook/examples/chapter_20/helloapp/hello/helloworld2_version2.go +++ b/eBook/examples/chapter_20/helloapp/hello/helloworld2_version2.go @@ -1,28 +1,28 @@ -package hello - -import ( - "appengine" - "appengine/user" - "fmt" - "net/http" -) - -func init() { - http.HandleFunc("/", handler) -} - -func handler(w http.ResponseWriter, r *http.Request) { - c := appengine.NewContext(r) - u := user.Current(c) - if u == nil { - url, err := user.LoginURL(c, r.URL.String()) - if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) - return - } - w.Header().Set("Location", url) - w.WriteHeader(http.StatusFound) - return - } - fmt.Fprintf(w, "Hello, %v!", u) -} +package hello + +import ( + "appengine" + "appengine/user" + "fmt" + "net/http" +) + +func init() { + http.HandleFunc("/", handler) +} + +func handler(w http.ResponseWriter, r *http.Request) { + c := appengine.NewContext(r) + u := user.Current(c) + if u == nil { + url, err := user.LoginURL(c, r.URL.String()) + if err != nil { + http.Error(w, err.String(), http.StatusInternalServerError) + return + } + w.Header().Set("Location", url) + w.WriteHeader(http.StatusFound) + return + } + fmt.Fprintf(w, "Hello, %v!", u) +} diff --git a/eBook/examples/chapter_20/helloapp/hello/helloworld2_version3.go b/eBook/examples/chapter_20/helloapp/hello/helloworld2_version3.go index 38a5f50..40a7e5d 100644 --- a/eBook/examples/chapter_20/helloapp/hello/helloworld2_version3.go +++ b/eBook/examples/chapter_20/helloapp/hello/helloworld2_version3.go @@ -1,46 +1,46 @@ -package hello - -import ( - "fmt" - "net/http" - "template" -) - -const guestbookForm = ` - - -
-
-
-
- - -` -const signTemplateHTML = ` - - -

You wrote:

-
{{html .}}
- - -` -var signTemplate = template.Must(template.New("sign").Parse(signTemplateHTML)) - -func init() { - http.HandleFunc("/", root) - http.HandleFunc("/sign", sign) -} - -func root(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/html") - fmt.Fprint(w, guestbookForm) -} - -func sign(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/html") - err := signTemplate.Execute(w, r.FormValue("content")) - if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) - } -} - +package hello + +import ( + "fmt" + "net/http" + "template" +) + +const guestbookForm = ` + + +
+
+
+
+ + +` +const signTemplateHTML = ` + + +

You wrote:

+
{{html .}}
+ + +` + +var signTemplate = template.Must(template.New("sign").Parse(signTemplateHTML)) + +func init() { + http.HandleFunc("/", root) + http.HandleFunc("/sign", sign) +} + +func root(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html") + fmt.Fprint(w, guestbookForm) +} + +func sign(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html") + err := signTemplate.Execute(w, r.FormValue("content")) + if err != nil { + http.Error(w, err.String(), http.StatusInternalServerError) + } +} diff --git a/eBook/examples/chapter_20/helloapp/hello/helloworld2_version4.go b/eBook/examples/chapter_20/helloapp/hello/helloworld2_version4.go index 51b72ae..d3d27fa 100644 --- a/eBook/examples/chapter_20/helloapp/hello/helloworld2_version4.go +++ b/eBook/examples/chapter_20/helloapp/hello/helloworld2_version4.go @@ -1,72 +1,73 @@ -package hello - -import ( - "appengine" - "appengine/datastore" - "appengine/user" - "net/http" - "template" - "time" -) - -const guestbookTemplateHTML = ` - - - {{range .}} - {{with .Author}} -

{{html .}} wrote:

- {{else}} -

An anonymous person wrote:

- {{end}} -
{{html .Content}}
-
{{html .Date}}
- {{end}} -
-
-
-
- - -` -var guestbookTemplate = template.Must(template.New("book").Parse(guestbookTemplateHTML)) - -type Greeting struct { - Author string - Content string - Date datastore.Time -} - -func init() { - http.HandleFunc("/", root) - http.HandleFunc("/sign", sign) -} - -func root(w http.ResponseWriter, r *http.Request) { - c := appengine.NewContext(r) - q := datastore.NewQuery("Greeting").Order("-Date").Limit(10) - greetings := make([]Greeting, 0, 10) - if _, err := q.GetAll(c, &greetings); err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) - return - } - if err := guestbookTemplate.Execute(w, greetings); err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) - } -} - -func sign(w http.ResponseWriter, r *http.Request) { - c := appengine.NewContext(r) - g := Greeting{ - Content: r.FormValue("content"), - Date: datastore.SecondsToTime(time.Seconds()), - } - if u := user.Current(c); u != nil { - g.Author = u.String() - } - _, err := datastore.Put(c, datastore.NewIncompleteKey(c, "Greeting", nil), &g) - if err != nil { - http.Error(w, err.String(), http.StatusInternalServerError) - return - } - http.Redirect(w, r, "/", http.StatusFound) -} +package hello + +import ( + "appengine" + "appengine/datastore" + "appengine/user" + "net/http" + "template" + "time" +) + +const guestbookTemplateHTML = ` + + + {{range .}} + {{with .Author}} +

{{html .}} wrote:

+ {{else}} +

An anonymous person wrote:

+ {{end}} +
{{html .Content}}
+
{{html .Date}}
+ {{end}} +
+
+
+
+ + +` + +var guestbookTemplate = template.Must(template.New("book").Parse(guestbookTemplateHTML)) + +type Greeting struct { + Author string + Content string + Date datastore.Time +} + +func init() { + http.HandleFunc("/", root) + http.HandleFunc("/sign", sign) +} + +func root(w http.ResponseWriter, r *http.Request) { + c := appengine.NewContext(r) + q := datastore.NewQuery("Greeting").Order("-Date").Limit(10) + greetings := make([]Greeting, 0, 10) + if _, err := q.GetAll(c, &greetings); err != nil { + http.Error(w, err.String(), http.StatusInternalServerError) + return + } + if err := guestbookTemplate.Execute(w, greetings); err != nil { + http.Error(w, err.String(), http.StatusInternalServerError) + } +} + +func sign(w http.ResponseWriter, r *http.Request) { + c := appengine.NewContext(r) + g := Greeting{ + Content: r.FormValue("content"), + Date: datastore.SecondsToTime(time.Seconds()), + } + if u := user.Current(c); u != nil { + g.Author = u.String() + } + _, err := datastore.Put(c, datastore.NewIncompleteKey(c, "Greeting", nil), &g) + if err != nil { + http.Error(w, err.String(), http.StatusInternalServerError) + return + } + http.Redirect(w, r, "/", http.StatusFound) +} diff --git a/eBook/examples/chapter_20/helloworld.go b/eBook/examples/chapter_20/helloworld.go index 70fa14d..3391fb7 100644 --- a/eBook/examples/chapter_20/helloworld.go +++ b/eBook/examples/chapter_20/helloworld.go @@ -1,16 +1,15 @@ -// helloworld.go -package helloworld - -import ( - "fmt" - "net/http" -) - -func init() { - http.HandleFunc("/", handle) -} - -func handle(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, "Hello, World! 세상아 안녕!! ") -} - +// helloworld.go +package helloworld + +import ( + "fmt" + "net/http" +) + +func init() { + http.HandleFunc("/", handle) +} + +func handle(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "Hello, World! 세상아 안녕!! ") +} diff --git a/eBook/examples/chapter_3/CandGo/c1.go b/eBook/examples/chapter_3/CandGo/c1.go index 77f1854..9b66469 100644 --- a/eBook/examples/chapter_3/CandGo/c1.go +++ b/eBook/examples/chapter_3/CandGo/c1.go @@ -1,13 +1,13 @@ -// c1.go -package rand - -// #include -import "C" - -func Random() int { - return int(C.random()) -} - -func Seed(i int) { - C.srandom(C.uint(i)) -} +// c1.go +package rand + +// #include +import "C" + +func Random() int { + return int(C.random()) +} + +func Seed(i int) { + C.srandom(C.uint(i)) +} diff --git a/eBook/examples/chapter_3/CandGo/c2.go b/eBook/examples/chapter_3/CandGo/c2.go index ba96ee4..d8ea5c6 100644 --- a/eBook/examples/chapter_3/CandGo/c2.go +++ b/eBook/examples/chapter_3/CandGo/c2.go @@ -1,13 +1,13 @@ -// c2.go -package print - -// #include -// #include -import "C" -import "unsafe" - -func Print(s string) { - cs := C.CString(s) - defer C.free(unsafe.Pointer(cs)) - C.fputs(cs, (*C.FILE)(C.stdout)) -} +// c2.go +package print + +// #include +// #include +import "C" +import "unsafe" + +func Print(s string) { + cs := C.CString(s) + defer C.free(unsafe.Pointer(cs)) + C.fputs(cs, (*C.FILE)(C.stdout)) +} diff --git a/eBook/examples/chapter_4/alias.go b/eBook/examples/chapter_4/alias.go index 5c0c829..150f10a 100644 --- a/eBook/examples/chapter_4/alias.go +++ b/eBook/examples/chapter_4/alias.go @@ -1,7 +1,7 @@ -package main - -import fm "fmt" // alias - -func main() { - fm.Println("hello, world") -} +package main + +import fm "fmt" // alias + +func main() { + fm.Println("hello, world") +} diff --git a/eBook/examples/chapter_4/casting.go b/eBook/examples/chapter_4/casting.go index cacf560..65ad643 100644 --- a/eBook/examples/chapter_4/casting.go +++ b/eBook/examples/chapter_4/casting.go @@ -1,18 +1,20 @@ -package main -import "fmt" - -func main() { - var n int16 = 34 - var m int32 - -// compiler error: cannot use n (type int16) as type int32 in assignment - //m = n - m = int32(n) - - fmt.Printf("32 bit int is: %d\n", m) - fmt.Printf("16 bit int is: %d\n", n) -} -/* Output: -32 bit int is: 34 -16 bit int is: 34 -*/ \ No newline at end of file +package main + +import "fmt" + +func main() { + var n int16 = 34 + var m int32 + + // compiler error: cannot use n (type int16) as type int32 in assignment + //m = n + m = int32(n) + + fmt.Printf("32 bit int is: %d\n", m) + fmt.Printf("16 bit int is: %d\n", n) +} + +/* Output: +32 bit int is: 34 +16 bit int is: 34 +*/ diff --git a/eBook/examples/chapter_4/char.go b/eBook/examples/chapter_4/char.go index e450ab4..0c2f1ce 100644 --- a/eBook/examples/chapter_4/char.go +++ b/eBook/examples/chapter_4/char.go @@ -1,22 +1,23 @@ -// char.go -package main - -import ( - "fmt" -) - -func main() { - var ch int = '\u0041' - var ch2 int = '\u03B2' - var ch3 int = '\U00101234' - fmt.Printf("%d - %d - %d\n", ch, ch2, ch3) - fmt.Printf("%c - %c - %c\n", ch, ch2, ch3) - fmt.Printf("%X - %X - %X\n", ch, ch2, ch3) - fmt.Printf("%U - %U - %U", ch, ch2, ch3) -} -/* Ouput: -65 - 946 - 1053236 -A - β - 􁈴 -41 - 3B2 - 101234 -U+0041 - U+03B2 - U+101234 -*/ \ No newline at end of file +// char.go +package main + +import ( + "fmt" +) + +func main() { + var ch int = '\u0041' + var ch2 int = '\u03B2' + var ch3 int = '\U00101234' + fmt.Printf("%d - %d - %d\n", ch, ch2, ch3) + fmt.Printf("%c - %c - %c\n", ch, ch2, ch3) + fmt.Printf("%X - %X - %X\n", ch, ch2, ch3) + fmt.Printf("%U - %U - %U", ch, ch2, ch3) +} + +/* Ouput: +65 - 946 - 1053236 +A - β - 􁈴 +41 - 3B2 - 101234 +U+0041 - U+03B2 - U+101234 +*/ diff --git a/eBook/examples/chapter_4/count_substring.go b/eBook/examples/chapter_4/count_substring.go index d9927a6..e97712f 100644 --- a/eBook/examples/chapter_4/count_substring.go +++ b/eBook/examples/chapter_4/count_substring.go @@ -1,17 +1,17 @@ -package main - -import ( - "fmt" - "strings" -) - -func main() { - var str string = "Hello, how is it going, Hugo?" - var manyG = "gggggggggg" - - fmt.Printf("Number of H's in %s is: ", str) - fmt.Printf("%d\n", strings.Count(str, "H")) - - fmt.Printf("Number of double g's in %s is: ", manyG) - fmt.Printf("%d\n", strings.Count(manyG, "gg")) -} +package main + +import ( + "fmt" + "strings" +) + +func main() { + var str string = "Hello, how is it going, Hugo?" + var manyG = "gggggggggg" + + fmt.Printf("Number of H's in %s is: ", str) + fmt.Printf("%d\n", strings.Count(str, "H")) + + fmt.Printf("Number of double g's in %s is: ", manyG) + fmt.Printf("%d\n", strings.Count(manyG, "gg")) +} diff --git a/eBook/examples/chapter_4/function_calls_function.go b/eBook/examples/chapter_4/function_calls_function.go index 84509c9..8784a74 100644 --- a/eBook/examples/chapter_4/function_calls_function.go +++ b/eBook/examples/chapter_4/function_calls_function.go @@ -1,15 +1,17 @@ -package main -var a string -func main() { - a = "G" - print(a) - f1() -} -func f1() { - a := "O" - print(a) - f2() -} -func f2() { - print(a) -} \ No newline at end of file +package main + +var a string + +func main() { + a = "G" + print(a) + f1() +} +func f1() { + a := "O" + print(a) + f2() +} +func f2() { + print(a) +} diff --git a/eBook/examples/chapter_4/global_scope.go b/eBook/examples/chapter_4/global_scope.go index 558afce..2b5fbbc 100644 --- a/eBook/examples/chapter_4/global_scope.go +++ b/eBook/examples/chapter_4/global_scope.go @@ -1,14 +1,16 @@ -package main -var a = "G" -func main() { - n() - m() - n() -} -func n() { - print(a) -} -func m() { - a = "O" - print(a) -} \ No newline at end of file +package main + +var a = "G" + +func main() { + n() + m() + n() +} +func n() { + print(a) +} +func m() { + a = "O" + print(a) +} diff --git a/eBook/examples/chapter_4/gotemplate.go b/eBook/examples/chapter_4/gotemplate.go index aafb5ab..68de9ca 100644 --- a/eBook/examples/chapter_4/gotemplate.go +++ b/eBook/examples/chapter_4/gotemplate.go @@ -1,30 +1,30 @@ -package main - -import ( - "fmt" -) - -const c = "C" - -var v int = 5 - -type T struct{} - -func init() { - // initialization of package -} - -func main() { - var a int - Func1() - // ... - fmt.Println(a) -} - -func (t T) Method1() { - //... -} - -func Func1() { // exported function Func1 - //... -} +package main + +import ( + "fmt" +) + +const c = "C" + +var v int = 5 + +type T struct{} + +func init() { + // initialization of package +} + +func main() { + var a int + Func1() + // ... + fmt.Println(a) +} + +func (t T) Method1() { + //... +} + +func Func1() { // exported function Func1 + //... +} diff --git a/eBook/examples/chapter_4/hello_world.go b/eBook/examples/chapter_4/hello_world.go index 8e4e589..635db7a 100644 --- a/eBook/examples/chapter_4/hello_world.go +++ b/eBook/examples/chapter_4/hello_world.go @@ -1,7 +1,7 @@ -package main - -import "fmt" - -func main() { - fmt.Println("hello, world") -} +package main + +import "fmt" + +func main() { + fmt.Println("hello, world") +} diff --git a/eBook/examples/chapter_4/hello_world2.go b/eBook/examples/chapter_4/hello_world2.go index c52d126..e8e85c4 100644 --- a/eBook/examples/chapter_4/hello_world2.go +++ b/eBook/examples/chapter_4/hello_world2.go @@ -1,7 +1,7 @@ -package main - -import "fmt" // Package implementing formatted I/O. - -func main() { - fmt.Printf("Hello, world; or Καλημέρα κόσμε; or こんにちは 世界\n") -} +package main + +import "fmt" // Package implementing formatted I/O. + +func main() { + fmt.Printf("Hello, world; or Καλημέρα κόσμε; or こんにちは 世界\n") +} diff --git a/eBook/examples/chapter_4/index_in_string.go b/eBook/examples/chapter_4/index_in_string.go index abc9d07..2964bfa 100644 --- a/eBook/examples/chapter_4/index_in_string.go +++ b/eBook/examples/chapter_4/index_in_string.go @@ -1,21 +1,21 @@ -package main - -import ( - "fmt" - "strings" -) - -func main() { - var str string = "Hi, I'm Marc, Hi." - - fmt.Printf("The position of \"Marc\" is: ") - fmt.Printf("%d\n", strings.Index(str, "Marc")) - - fmt.Printf("The position of the first instance of \"Hi\" is: ") - fmt.Printf("%d\n", strings.Index(str, "Hi")) - fmt.Printf("The position of the last instance of \"Hi\" is: ") - fmt.Printf("%d\n", strings.LastIndex(str, "Hi")) - - fmt.Printf("The position of \"Burger\" is: ") - fmt.Printf("%d\n", strings.Index(str, "Burger")) -} +package main + +import ( + "fmt" + "strings" +) + +func main() { + var str string = "Hi, I'm Marc, Hi." + + fmt.Printf("The position of \"Marc\" is: ") + fmt.Printf("%d\n", strings.Index(str, "Marc")) + + fmt.Printf("The position of the first instance of \"Hi\" is: ") + fmt.Printf("%d\n", strings.Index(str, "Hi")) + fmt.Printf("The position of the last instance of \"Hi\" is: ") + fmt.Printf("%d\n", strings.LastIndex(str, "Hi")) + + fmt.Printf("The position of \"Burger\" is: ") + fmt.Printf("%d\n", strings.Index(str, "Burger")) +} diff --git a/eBook/examples/chapter_4/local_scope.go b/eBook/examples/chapter_4/local_scope.go index decff22..24ab265 100644 --- a/eBook/examples/chapter_4/local_scope.go +++ b/eBook/examples/chapter_4/local_scope.go @@ -1,12 +1,14 @@ -package main -var a = "G" -func main() { - n() - m() - n() -} -func n() { print(a) } -func m() { - a := "O" - print(a) -} \ No newline at end of file +package main + +var a = "G" + +func main() { + n() + m() + n() +} +func n() { print(a) } +func m() { + a := "O" + print(a) +} diff --git a/eBook/examples/chapter_4/pointer.go b/eBook/examples/chapter_4/pointer.go index 1ae2248..13c292b 100644 --- a/eBook/examples/chapter_4/pointer.go +++ b/eBook/examples/chapter_4/pointer.go @@ -1,12 +1,12 @@ -package main - -import "fmt" - -func main() { - var i1 = 5 - fmt.Printf("An integer: %d, its location in memory: %p\n", i1, &i1) - - var intP *int - intP = &i1 - fmt.Printf("The value at memory location %p is %d\n", intP, *intP) -} +package main + +import "fmt" + +func main() { + var i1 = 5 + fmt.Printf("An integer: %d, its location in memory: %p\n", i1, &i1) + + var intP *int + intP = &i1 + fmt.Printf("The value at memory location %p is %d\n", intP, *intP) +} diff --git a/eBook/examples/chapter_4/presuffix.go b/eBook/examples/chapter_4/presuffix.go index 7b4fd88..f19be72 100644 --- a/eBook/examples/chapter_4/presuffix.go +++ b/eBook/examples/chapter_4/presuffix.go @@ -1,14 +1,15 @@ -package main - -import ( - "fmt" - "strings" -) - -func main() { - var str string = "This is an example of a string" - - fmt.Printf("T/F? Does the string \"%s\" have prefix %s? ", str, "Th") - fmt.Printf("%t\n", strings.HasPrefix(str, "Th")) -} -// Output: T/F? Does the string "This is an example of a string" have prefix Th? true \ No newline at end of file +package main + +import ( + "fmt" + "strings" +) + +func main() { + var str string = "This is an example of a string" + + fmt.Printf("T/F? Does the string \"%s\" have prefix %s? ", str, "Th") + fmt.Printf("%t\n", strings.HasPrefix(str, "Th")) +} + +// Output: T/F? Does the string "This is an example of a string" have prefix Th? true diff --git a/eBook/examples/chapter_4/random.go b/eBook/examples/chapter_4/random.go index 2c5c604..78aa352 100644 --- a/eBook/examples/chapter_4/random.go +++ b/eBook/examples/chapter_4/random.go @@ -1,28 +1,29 @@ -package main - -import ( - "fmt" - "math/rand" - "time" -) - -func main() { - for i := 0; i < 10; i++ { - a := rand.Int() - fmt.Printf("%d / ", a) - } - for i := 0; i < 5; i++ { - r := rand.Intn(8) - fmt.Printf("%d / ", r) - } - fmt.Println() - timens := int64(time.Now().Nanosecond()) - rand.Seed(timens) - for i := 0; i < 10; i++ { - fmt.Printf("%2.2f / ", 100*rand.Float32()) - } -} -/* Output: -134020434 / 1597969999 / 1721070109 / 2068675587 / 1237770961 / 220031192 / 2031484958 / 583324308 / 958990240 / 413002649 / 6 / 7 / 2 / 1 / 0 / -22.84 / 10.12 / 44.32 / 58.58 / 15.49 / 12.23 / 30.16 / 88.48 / 34.26 / 27.18 / -*/ +package main + +import ( + "fmt" + "math/rand" + "time" +) + +func main() { + for i := 0; i < 10; i++ { + a := rand.Int() + fmt.Printf("%d / ", a) + } + for i := 0; i < 5; i++ { + r := rand.Intn(8) + fmt.Printf("%d / ", r) + } + fmt.Println() + timens := int64(time.Now().Nanosecond()) + rand.Seed(timens) + for i := 0; i < 10; i++ { + fmt.Printf("%2.2f / ", 100*rand.Float32()) + } +} + +/* Output: +134020434 / 1597969999 / 1721070109 / 2068675587 / 1237770961 / 220031192 / 2031484958 / 583324308 / 958990240 / 413002649 / 6 / 7 / 2 / 1 / 0 / +22.84 / 10.12 / 44.32 / 58.58 / 15.49 / 12.23 / 30.16 / 88.48 / 34.26 / 27.18 / +*/ diff --git a/eBook/examples/chapter_4/repeat_string.go b/eBook/examples/chapter_4/repeat_string.go index 426e76f..043ee14 100644 --- a/eBook/examples/chapter_4/repeat_string.go +++ b/eBook/examples/chapter_4/repeat_string.go @@ -1,14 +1,14 @@ -package main - -import ( - "fmt" - "strings" -) - -func main() { - var origS string = "Hi there! " - var newS string - - newS = strings.Repeat(origS, 3) - fmt.Printf("The new repeated string is: %s\n", newS) -} +package main + +import ( + "fmt" + "strings" +) + +func main() { + var origS string = "Hi there! " + var newS string + + newS = strings.Repeat(origS, 3) + fmt.Printf("The new repeated string is: %s\n", newS) +} diff --git a/eBook/examples/chapter_4/string_conversion.go b/eBook/examples/chapter_4/string_conversion.go index 61a6ff1..4b27c94 100644 --- a/eBook/examples/chapter_4/string_conversion.go +++ b/eBook/examples/chapter_4/string_conversion.go @@ -1,20 +1,20 @@ -package main - -import ( - "fmt" - "strconv" -) - -func main() { - var orig string = "666" - var an int - var newS string - - fmt.Printf("The size of ints is: %d\n", strconv.IntSize) - - an, _ = strconv.Atoi(orig) - fmt.Printf("The integer is: %d\n", an) - an = an + 5 - newS = strconv.Itoa(an) - fmt.Printf("The new string is: %s\n", newS) -} +package main + +import ( + "fmt" + "strconv" +) + +func main() { + var orig string = "666" + var an int + var newS string + + fmt.Printf("The size of ints is: %d\n", strconv.IntSize) + + an, _ = strconv.Atoi(orig) + fmt.Printf("The integer is: %d\n", an) + an = an + 5 + newS = strconv.Itoa(an) + fmt.Printf("The new string is: %s\n", newS) +} diff --git a/eBook/examples/chapter_4/string_pointer.go b/eBook/examples/chapter_4/string_pointer.go index 7448423..abd62bd 100644 --- a/eBook/examples/chapter_4/string_pointer.go +++ b/eBook/examples/chapter_4/string_pointer.go @@ -1,13 +1,13 @@ -package main - -import "fmt" - -func main() { - s := "good bye" - var p *string = &s - *p = "ciao" - - fmt.Printf("Here is the pointer p: %p\n", p) // prints address - fmt.Printf("Here is the string *p: %s\n", *p) // prints string - fmt.Printf("Here is the string s: %s\n", s) // prints same string -} +package main + +import "fmt" + +func main() { + s := "good bye" + var p *string = &s + *p = "ciao" + + fmt.Printf("Here is the pointer p: %p\n", p) // prints address + fmt.Printf("Here is the string *p: %s\n", *p) // prints string + fmt.Printf("Here is the string s: %s\n", s) // prints same string +} diff --git a/eBook/examples/chapter_4/strings_splitjoin.go b/eBook/examples/chapter_4/strings_splitjoin.go index a31d43c..542cf9a 100644 --- a/eBook/examples/chapter_4/strings_splitjoin.go +++ b/eBook/examples/chapter_4/strings_splitjoin.go @@ -1,33 +1,34 @@ -// strings.go -package main - -import ( - "fmt" - "strings" -) - -func main() { - str := "The quick brown fox jumps over the lazy dog" - sl := strings.Fields(str) - fmt.Printf("Splitted in slice: %v\n", sl) - for _, val := range sl { - fmt.Printf("%s - ", val) - } - fmt.Println() - str2 := "GO1|The ABC of Go|25" - sl2 := strings.Split(str2, "|") - fmt.Printf("Splitted in slice: %v\n", sl2) - for _, val := range sl2 { - fmt.Printf("%s - ", val) - } - fmt.Println() - str3 := strings.Join(sl2,";") - fmt.Printf("sl2 joined by ;: %s\n", str3) -} -/* Output: -Splitted in slice: [The quick brown fox jumps over the lazy dog] -The - quick - brown - fox - jumps - over - the - lazy - dog - -Splitted in slice: [GO1 The ABC of Go 25] -GO1 - The ABC of Go - 25 - -sl2 joined by ;: GO1;The ABC of Go;25 -*/ \ No newline at end of file +// strings.go +package main + +import ( + "fmt" + "strings" +) + +func main() { + str := "The quick brown fox jumps over the lazy dog" + sl := strings.Fields(str) + fmt.Printf("Splitted in slice: %v\n", sl) + for _, val := range sl { + fmt.Printf("%s - ", val) + } + fmt.Println() + str2 := "GO1|The ABC of Go|25" + sl2 := strings.Split(str2, "|") + fmt.Printf("Splitted in slice: %v\n", sl2) + for _, val := range sl2 { + fmt.Printf("%s - ", val) + } + fmt.Println() + str3 := strings.Join(sl2, ";") + fmt.Printf("sl2 joined by ;: %s\n", str3) +} + +/* Output: +Splitted in slice: [The quick brown fox jumps over the lazy dog] +The - quick - brown - fox - jumps - over - the - lazy - dog - +Splitted in slice: [GO1 The ABC of Go 25] +GO1 - The ABC of Go - 25 - +sl2 joined by ;: GO1;The ABC of Go;25 +*/ diff --git a/eBook/examples/chapter_4/testcrash.go b/eBook/examples/chapter_4/testcrash.go index faff80f..42e2cf5 100644 --- a/eBook/examples/chapter_4/testcrash.go +++ b/eBook/examples/chapter_4/testcrash.go @@ -1,11 +1,12 @@ -// testcrash.go -// compiles , but crashes -package main - -func main() { - var p *int = nil - *p = 0 - -} -// in Windows: stops only with: -// runtime error: invalid memory address or nil pointer dereference +// testcrash.go +// compiles , but crashes +package main + +func main() { + var p *int = nil + *p = 0 + +} + +// in Windows: stops only with: +// runtime error: invalid memory address or nil pointer dereference diff --git a/eBook/examples/chapter_4/time.go b/eBook/examples/chapter_4/time.go index 4ebf08e..393c4d6 100644 --- a/eBook/examples/chapter_4/time.go +++ b/eBook/examples/chapter_4/time.go @@ -1,27 +1,27 @@ -package main - -import ( - "fmt" - "time" -) - -var week time.Duration - -func main() { - t := time.Now() - fmt.Println(t) // Wed Dec 21 09:52:14 +0100 RST 2011 - fmt.Printf("%02d.%02d.%4d\n", t.Day(), t.Month(), t.Year()) // 21.12.2011 - t = time.Now().UTC() - fmt.Println(t) // Wed Dec 21 08:52:14 +0000 UTC 2011 - fmt.Println(time.Now()) // Wed Dec 21 09:52:14 +0100 RST 2011 - // calculating times: - week = 60 * 60 * 24 * 7 * 1e9 // must be in nanosec - week_from_now := t.Add(week) - fmt.Println(week_from_now) // Wed Dec 28 08:52:14 +0000 UTC 2011 - // formatting times: - fmt.Println(t.Format(time.RFC822)) // 21 Dec 11 0852 UTC - fmt.Println(t.Format(time.ANSIC)) // Wed Dec 21 08:56:34 2011 - fmt.Println(t.Format("02 Jan 2006 15:04")) // 21 Dec 2011 08:52 - s := t.Format("20060102") - fmt.Println(t, "=>", s) // Wed Dec 21 08:52:14 +0000 UTC 2011 => 20111221 -} +package main + +import ( + "fmt" + "time" +) + +var week time.Duration + +func main() { + t := time.Now() + fmt.Println(t) // Wed Dec 21 09:52:14 +0100 RST 2011 + fmt.Printf("%02d.%02d.%4d\n", t.Day(), t.Month(), t.Year()) // 21.12.2011 + t = time.Now().UTC() + fmt.Println(t) // Wed Dec 21 08:52:14 +0000 UTC 2011 + fmt.Println(time.Now()) // Wed Dec 21 09:52:14 +0100 RST 2011 + // calculating times: + week = 60 * 60 * 24 * 7 * 1e9 // must be in nanosec + week_from_now := t.Add(week) + fmt.Println(week_from_now) // Wed Dec 28 08:52:14 +0000 UTC 2011 + // formatting times: + fmt.Println(t.Format(time.RFC822)) // 21 Dec 11 0852 UTC + fmt.Println(t.Format(time.ANSIC)) // Wed Dec 21 08:56:34 2011 + fmt.Println(t.Format("02 Jan 2006 15:04")) // 21 Dec 2011 08:52 + s := t.Format("20060102") + fmt.Println(t, "=>", s) // Wed Dec 21 08:52:14 +0000 UTC 2011 => 20111221 +} diff --git a/eBook/examples/chapter_4/toupper_lower.go b/eBook/examples/chapter_4/toupper_lower.go index 6cb2b36..a170831 100644 --- a/eBook/examples/chapter_4/toupper_lower.go +++ b/eBook/examples/chapter_4/toupper_lower.go @@ -1,18 +1,18 @@ -package main - -import ( - "fmt" - "strings" -) - -func main() { - var orig string = "Hey, how are you George?" - var lower string - var upper string - - fmt.Printf("The original string is: %s\n", orig) - lower = strings.ToLower(orig) - fmt.Printf("The lowercase string is: %s\n", lower) - upper = strings.ToUpper(orig) - fmt.Printf("The uppercase string is: %s\n", upper) -} +package main + +import ( + "fmt" + "strings" +) + +func main() { + var orig string = "Hey, how are you George?" + var lower string + var upper string + + fmt.Printf("The original string is: %s\n", orig) + lower = strings.ToLower(orig) + fmt.Printf("The lowercase string is: %s\n", lower) + upper = strings.ToUpper(orig) + fmt.Printf("The uppercase string is: %s\n", upper) +} diff --git a/eBook/examples/chapter_4/type.go b/eBook/examples/chapter_4/type.go index a541098..55e53c7 100644 --- a/eBook/examples/chapter_4/type.go +++ b/eBook/examples/chapter_4/type.go @@ -1,11 +1,11 @@ -package main - -import "fmt" - -type TZ int - -func main() { - var a, b TZ = 3, 4 - c := a + b - fmt.Printf("c has the value: %d", c) -} \ No newline at end of file +package main + +import "fmt" + +type TZ int + +func main() { + var a, b TZ = 3, 4 + c := a + b + fmt.Printf("c has the value: %d", c) +} diff --git a/eBook/examples/chapter_4/type_mixing.go b/eBook/examples/chapter_4/type_mixing.go index 1814249..1df0ed9 100644 --- a/eBook/examples/chapter_4/type_mixing.go +++ b/eBook/examples/chapter_4/type_mixing.go @@ -1,9 +1,9 @@ -package main - -func main() { - var a int - var b int32 - a = 15 - b = a + a // compiler error - b = b + 5 // ok: 5 is a constant -} \ No newline at end of file +package main + +func main() { + var a int + var b int32 + a = 15 + b = a + a // compiler error + b = b + 5 // ok: 5 is a constant +} diff --git a/eBook/examples/chapter_4/use_init.go b/eBook/examples/chapter_4/use_init.go index 9b9a62f..9a38fb4 100644 --- a/eBook/examples/chapter_4/use_init.go +++ b/eBook/examples/chapter_4/use_init.go @@ -1,12 +1,12 @@ -package main - -import ( - "fmt" - "./trans" -) - -var twoPi = 2 * trans.Pi // decl computes twoPi - -func main() { - fmt.Printf("2*Pi = %g\n", twoPi) // 2*Pi = 6.283185307179586 -} +package main + +import ( + "./trans" + "fmt" +) + +var twoPi = 2 * trans.Pi // decl computes twoPi + +func main() { + fmt.Printf("2*Pi = %g\n", twoPi) // 2*Pi = 6.283185307179586 +} diff --git a/eBook/examples/chapter_4/user_init.go b/eBook/examples/chapter_4/user_init.go index 6f4dd20..811321c 100644 --- a/eBook/examples/chapter_4/user_init.go +++ b/eBook/examples/chapter_4/user_init.go @@ -1,9 +1,12 @@ -package main -import ( - "fmt" - "./trans" -) -var twoPi = 2 * trans.Pi -func main() { - fmt.Printf("2*Pi = %g\n", twoPi) // 2*Pi = 6.283185307179586 -} \ No newline at end of file +package main + +import ( + "./trans" + "fmt" +) + +var twoPi = 2 * trans.Pi + +func main() { + fmt.Printf("2*Pi = %g\n", twoPi) // 2*Pi = 6.283185307179586 +} diff --git a/eBook/examples/chapter_5/booleans.go b/eBook/examples/chapter_5/booleans.go index 3b29401..bcf145f 100644 --- a/eBook/examples/chapter_5/booleans.go +++ b/eBook/examples/chapter_5/booleans.go @@ -1,12 +1,12 @@ -package main - -import "fmt" - -func main() { - bool1 := true - if bool1 { - fmt.Printf("The value is true\n") - } else { - fmt.Printf("The value is false\n") - } -} +package main + +import "fmt" + +func main() { + bool1 := true + if bool1 { + fmt.Printf("The value is true\n") + } else { + fmt.Printf("The value is false\n") + } +} diff --git a/eBook/examples/chapter_5/for1.go b/eBook/examples/chapter_5/for1.go index 66efa90..79f958a 100644 --- a/eBook/examples/chapter_5/for1.go +++ b/eBook/examples/chapter_5/for1.go @@ -1,9 +1,9 @@ -package main - -import "fmt" - -func main() { - for i := 0; i < 5; i++ { - fmt.Printf("This is the %d iteration\n", i) - } -} +package main + +import "fmt" + +func main() { + for i := 0; i < 5; i++ { + fmt.Printf("This is the %d iteration\n", i) + } +} diff --git a/eBook/examples/chapter_5/for2.go b/eBook/examples/chapter_5/for2.go index dceb993..bf9b294 100644 --- a/eBook/examples/chapter_5/for2.go +++ b/eBook/examples/chapter_5/for2.go @@ -1,12 +1,12 @@ -package main - -import "fmt" - -func main() { - var i int = 5 - - for i >= 0 { - i = i - 1 - fmt.Printf("The variable i is now: %d\n", i) - } -} +package main + +import "fmt" + +func main() { + var i int = 5 + + for i >= 0 { + i = i - 1 + fmt.Printf("The variable i is now: %d\n", i) + } +} diff --git a/eBook/examples/chapter_5/for3.go b/eBook/examples/chapter_5/for3.go index 7a045ae..62bd74b 100644 --- a/eBook/examples/chapter_5/for3.go +++ b/eBook/examples/chapter_5/for3.go @@ -1,15 +1,15 @@ -package main - -import "fmt" - -func main() { - var i int = 5 - - for { - i = i - 1 - fmt.Printf("The variable i is now: %d\n", i) - if i < 0 { - break - } - } -} +package main + +import "fmt" + +func main() { + var i int = 5 + + for { + i = i - 1 + fmt.Printf("The variable i is now: %d\n", i) + if i < 0 { + break + } + } +} diff --git a/eBook/examples/chapter_5/for4.go b/eBook/examples/chapter_5/for4.go index 6f5c7ab..649baed 100644 --- a/eBook/examples/chapter_5/for4.go +++ b/eBook/examples/chapter_5/for4.go @@ -1,13 +1,13 @@ -package main - -func main() { - for i:=0; i<3; i++ { - for j:=0; j<10; j++ { - if j>5 { - break - } - print(j) - } - print(" ") - } -} \ No newline at end of file +package main + +func main() { + for i := 0; i < 3; i++ { + for j := 0; j < 10; j++ { + if j > 5 { + break + } + print(j) + } + print(" ") + } +} diff --git a/eBook/examples/chapter_5/for5.go b/eBook/examples/chapter_5/for5.go index 475b926..6e1135e 100644 --- a/eBook/examples/chapter_5/for5.go +++ b/eBook/examples/chapter_5/for5.go @@ -1,11 +1,11 @@ -package main - -func main() { - for i := 0; i < 10; i++ { - if i == 5 { - continue - } - print(i) - print(" ") - } -} +package main + +func main() { + for i := 0; i < 10; i++ { + if i == 5 { + continue + } + print(i) + print(" ") + } +} diff --git a/eBook/examples/chapter_5/for6.go b/eBook/examples/chapter_5/for6.go index bf04e78..81a96d8 100644 --- a/eBook/examples/chapter_5/for6.go +++ b/eBook/examples/chapter_5/for6.go @@ -1,17 +1,17 @@ -package main - -import "fmt" - -func main() { - -LABEL1: - for i := 0; i <= 5; i++ { - for j := 0; j <= 5; j++ { - if j == 4 { - continue LABEL1 - } - fmt.Printf("i is: %d, and j is: %d\n", i, j) - } - } - -} +package main + +import "fmt" + +func main() { + +LABEL1: + for i := 0; i <= 5; i++ { + for j := 0; j <= 5; j++ { + if j == 4 { + continue LABEL1 + } + fmt.Printf("i is: %d, and j is: %d\n", i, j) + } + } + +} diff --git a/eBook/examples/chapter_5/for_string.go b/eBook/examples/chapter_5/for_string.go index 97b8d59..4d59038 100644 --- a/eBook/examples/chapter_5/for_string.go +++ b/eBook/examples/chapter_5/for_string.go @@ -1,57 +1,58 @@ -// for_string.go -package main - -import "fmt" - -func main() { - str := "Go is a beautiful language!" - fmt.Printf("The length of str is: %d\n", len(str)) - for ix :=0; ix < len(str); ix++ { - fmt.Printf("Character on position %d is: %c \n", ix, str[ix]) - } - str2 := "日本語" - fmt.Printf("The length of str2 is: %d\n", len(str2)) - for ix :=0; ix < len(str2); ix++ { - fmt.Printf("Character on position %d is: %c \n", ix, str2[ix]) - } -} -/* Output: -The length of str is: 27 -Character on position 0 is: G -Character on position 1 is: o -Character on position 2 is: -Character on position 3 is: i -Character on position 4 is: s -Character on position 5 is: -Character on position 6 is: a -Character on position 7 is: -Character on position 8 is: b -Character on position 9 is: e -Character on position 10 is: a -Character on position 11 is: u -Character on position 12 is: t -Character on position 13 is: i -Character on position 14 is: f -Character on position 15 is: u -Character on position 16 is: l -Character on position 17 is: -Character on position 18 is: l -Character on position 19 is: a -Character on position 20 is: n -Character on position 21 is: g -Character on position 22 is: u -Character on position 23 is: a -Character on position 24 is: g -Character on position 25 is: e -Character on position 26 is: ! -The length of str2 is: 9 -Character on position 0 is: æ -Character on position 1 is: — -Character on position 2 is: ¥ -Character on position 3 is: æ -Character on position 4 is: œ -Character on position 5 is: ¬ -Character on position 6 is: è -Character on position 7 is: ª -Character on position 8 is: ž -*/ \ No newline at end of file +// for_string.go +package main + +import "fmt" + +func main() { + str := "Go is a beautiful language!" + fmt.Printf("The length of str is: %d\n", len(str)) + for ix := 0; ix < len(str); ix++ { + fmt.Printf("Character on position %d is: %c \n", ix, str[ix]) + } + str2 := "日本語" + fmt.Printf("The length of str2 is: %d\n", len(str2)) + for ix := 0; ix < len(str2); ix++ { + fmt.Printf("Character on position %d is: %c \n", ix, str2[ix]) + } +} + +/* Output: +The length of str is: 27 +Character on position 0 is: G +Character on position 1 is: o +Character on position 2 is: +Character on position 3 is: i +Character on position 4 is: s +Character on position 5 is: +Character on position 6 is: a +Character on position 7 is: +Character on position 8 is: b +Character on position 9 is: e +Character on position 10 is: a +Character on position 11 is: u +Character on position 12 is: t +Character on position 13 is: i +Character on position 14 is: f +Character on position 15 is: u +Character on position 16 is: l +Character on position 17 is: +Character on position 18 is: l +Character on position 19 is: a +Character on position 20 is: n +Character on position 21 is: g +Character on position 22 is: u +Character on position 23 is: a +Character on position 24 is: g +Character on position 25 is: e +Character on position 26 is: ! +The length of str2 is: 9 +Character on position 0 is: æ +Character on position 1 is: — +Character on position 2 is: ¥ +Character on position 3 is: æ +Character on position 4 is: œ +Character on position 5 is: ¬ +Character on position 6 is: è +Character on position 7 is: ª +Character on position 8 is: ž +*/ diff --git a/eBook/examples/chapter_5/goto.go b/eBook/examples/chapter_5/goto.go index c36a7ea..bddd755 100644 --- a/eBook/examples/chapter_5/goto.go +++ b/eBook/examples/chapter_5/goto.go @@ -1,12 +1,12 @@ -package main - -func main() { - i:=0 - HERE: - print(i) - i++ - if i==5 { - return - } - goto HERE -} \ No newline at end of file +package main + +func main() { + i := 0 +HERE: + print(i) + i++ + if i == 5 { + return + } + goto HERE +} diff --git a/eBook/examples/chapter_5/goto2.go b/eBook/examples/chapter_5/goto2.go index 118f47c..9ebce7c 100644 --- a/eBook/examples/chapter_5/goto2.go +++ b/eBook/examples/chapter_5/goto2.go @@ -1,13 +1,13 @@ -// compile error goto2.go:8: goto TARGET jumps over declaration of b at goto2.go:8 -package main - -import "fmt" - -func main() { - a := 1 - goto TARGET // compile error - b := 9 - TARGET: - b += a - fmt.Printf("a is %v *** b is %v", a, b) -} \ No newline at end of file +// compile error goto2.go:8: goto TARGET jumps over declaration of b at goto2.go:8 +package main + +import "fmt" + +func main() { + a := 1 + goto TARGET // compile error + b := 9 +TARGET: + b += a + fmt.Printf("a is %v *** b is %v", a, b) +} diff --git a/eBook/examples/chapter_5/ifelse.go b/eBook/examples/chapter_5/ifelse.go index aad629e..0b8dc61 100644 --- a/eBook/examples/chapter_5/ifelse.go +++ b/eBook/examples/chapter_5/ifelse.go @@ -1,22 +1,22 @@ -package main - -import "fmt" - -func main() { - var first int = 10 - var cond int - - if first <= 0 { - fmt.Printf("first is less than or equal to 0\n") - } else if first > 0 && first < 5 { - fmt.Printf("first is between 0 and 5\n") - } else { - fmt.Printf("first is 5 or greater\n") - } - - if cond = 5; cond > 10 { - fmt.Printf("cond is greater than 10\n") - } else { - fmt.Printf("cond is not greater than 10\n") - } -} +package main + +import "fmt" + +func main() { + var first int = 10 + var cond int + + if first <= 0 { + fmt.Printf("first is less than or equal to 0\n") + } else if first > 0 && first < 5 { + fmt.Printf("first is between 0 and 5\n") + } else { + fmt.Printf("first is 5 or greater\n") + } + + if cond = 5; cond > 10 { + fmt.Printf("cond is greater than 10\n") + } else { + fmt.Printf("cond is not greater than 10\n") + } +} diff --git a/eBook/examples/chapter_5/range_string.go b/eBook/examples/chapter_5/range_string.go index 465b392..5a00c29 100644 --- a/eBook/examples/chapter_5/range_string.go +++ b/eBook/examples/chapter_5/range_string.go @@ -1,80 +1,81 @@ -package main - -import "fmt" - -func main() { - str := "Go is a beautiful language!" - fmt.Printf("The length of str is: %d\n", len(str)) - for pos, char := range str { - fmt.Printf("Character on position %d is: %c \n", pos, char) - } - fmt.Println() - str2 := "Chinese: 日本語" - fmt.Printf("The length of str2 is: %d\n", len(str2)) - for pos, char := range str2 { - fmt.Printf("character %c starts at byte position %d\n", char, pos) - } - fmt.Println() - fmt.Println("index int(rune) rune char bytes") - for index, rune := range str2 { - fmt.Printf("%-2d %d %U '%c' % X\n", index, rune, rune, rune, []byte(string(rune))) - } -} -/* Output: -The length of str is: 27 -Character on position 0 is: G -Character on position 1 is: o -Character on position 2 is: -Character on position 3 is: i -Character on position 4 is: s -Character on position 5 is: -Character on position 6 is: a -Character on position 7 is: -Character on position 8 is: b -Character on position 9 is: e -Character on position 10 is: a -Character on position 11 is: u -Character on position 12 is: t -Character on position 13 is: i -Character on position 14 is: f -Character on position 15 is: u -Character on position 16 is: l -Character on position 17 is: -Character on position 18 is: l -Character on position 19 is: a -Character on position 20 is: n -Character on position 21 is: g -Character on position 22 is: u -Character on position 23 is: a -Character on position 24 is: g -Character on position 25 is: e -Character on position 26 is: ! - -The length of str2 is: 18 -character C starts at byte position 0 -character h starts at byte position 1 -character i starts at byte position 2 -character n starts at byte position 3 -character e starts at byte position 4 -character s starts at byte position 5 -character e starts at byte position 6 -character : starts at byte position 7 -character starts at byte position 8 -character 日 starts at byte position 9 -character 本 starts at byte position 12 -character 語 starts at byte position 15 - -index int(rune) rune char bytes -0 67 U+0043 'C' 43 -1 104 U+0068 'h' 68 -2 105 U+0069 'i' 69 -3 110 U+006E 'n' 6E -4 101 U+0065 'e' 65 -5 115 U+0073 's' 73 -6 101 U+0065 'e' 65 -7 58 U+003A ':' 3A -8 32 U+0020 ' ' 20 -9 26085 U+65E5 '日' E6 97 A5 -12 26412 U+672C '本' E6 9C AC -15 35486 U+8A9E '語' E8 AA 9E -*/ +package main + +import "fmt" + +func main() { + str := "Go is a beautiful language!" + fmt.Printf("The length of str is: %d\n", len(str)) + for pos, char := range str { + fmt.Printf("Character on position %d is: %c \n", pos, char) + } + fmt.Println() + str2 := "Chinese: 日本語" + fmt.Printf("The length of str2 is: %d\n", len(str2)) + for pos, char := range str2 { + fmt.Printf("character %c starts at byte position %d\n", char, pos) + } + fmt.Println() + fmt.Println("index int(rune) rune char bytes") + for index, rune := range str2 { + fmt.Printf("%-2d %d %U '%c' % X\n", index, rune, rune, rune, []byte(string(rune))) + } +} + +/* Output: +The length of str is: 27 +Character on position 0 is: G +Character on position 1 is: o +Character on position 2 is: +Character on position 3 is: i +Character on position 4 is: s +Character on position 5 is: +Character on position 6 is: a +Character on position 7 is: +Character on position 8 is: b +Character on position 9 is: e +Character on position 10 is: a +Character on position 11 is: u +Character on position 12 is: t +Character on position 13 is: i +Character on position 14 is: f +Character on position 15 is: u +Character on position 16 is: l +Character on position 17 is: +Character on position 18 is: l +Character on position 19 is: a +Character on position 20 is: n +Character on position 21 is: g +Character on position 22 is: u +Character on position 23 is: a +Character on position 24 is: g +Character on position 25 is: e +Character on position 26 is: ! + +The length of str2 is: 18 +character C starts at byte position 0 +character h starts at byte position 1 +character i starts at byte position 2 +character n starts at byte position 3 +character e starts at byte position 4 +character s starts at byte position 5 +character e starts at byte position 6 +character : starts at byte position 7 +character starts at byte position 8 +character 日 starts at byte position 9 +character 本 starts at byte position 12 +character 語 starts at byte position 15 + +index int(rune) rune char bytes +0 67 U+0043 'C' 43 +1 104 U+0068 'h' 68 +2 105 U+0069 'i' 69 +3 110 U+006E 'n' 6E +4 101 U+0065 'e' 65 +5 115 U+0073 's' 73 +6 101 U+0065 'e' 65 +7 58 U+003A ':' 3A +8 32 U+0020 ' ' 20 +9 26085 U+65E5 '日' E6 97 A5 +12 26412 U+672C '本' E6 9C AC +15 35486 U+8A9E '語' E8 AA 9E +*/ diff --git a/eBook/examples/chapter_5/string_conversion2.go b/eBook/examples/chapter_5/string_conversion2.go index 49e9479..bbc0527 100644 --- a/eBook/examples/chapter_5/string_conversion2.go +++ b/eBook/examples/chapter_5/string_conversion2.go @@ -1,25 +1,25 @@ -package main - -import ( - "fmt" - "strconv" -) - -func main() { - var orig string = "ABC" - // var an int - var newS string - // var err error - - fmt.Printf("The size of ints is: %d\n", strconv.IntSize) - // anInt, err = strconv.Atoi(origStr) - an, err := strconv.Atoi(orig) - if err != nil { - fmt.Printf("orig %s is not an integer - exiting with error\n", orig) - return - } - fmt.Printf("The integer is %d\n", an) - an = an + 5 - newS = strconv.Itoa(an) - fmt.Printf("The new string is: %s\n", newS) -} +package main + +import ( + "fmt" + "strconv" +) + +func main() { + var orig string = "ABC" + // var an int + var newS string + // var err error + + fmt.Printf("The size of ints is: %d\n", strconv.IntSize) + // anInt, err = strconv.Atoi(origStr) + an, err := strconv.Atoi(orig) + if err != nil { + fmt.Printf("orig %s is not an integer - exiting with error\n", orig) + return + } + fmt.Printf("The integer is %d\n", an) + an = an + 5 + newS = strconv.Itoa(an) + fmt.Printf("The new string is: %s\n", newS) +} diff --git a/eBook/examples/chapter_5/switch1.go b/eBook/examples/chapter_5/switch1.go index e5a2fa0..ca0d038 100644 --- a/eBook/examples/chapter_5/switch1.go +++ b/eBook/examples/chapter_5/switch1.go @@ -1,16 +1,16 @@ -package main - -import "fmt" - -func main() { - var num1 int = 100 - - switch num1 { - case 98, 99: - fmt.Println("It's equal to 98") - case 100: - fmt.Println("It's equal to 100") - default: - fmt.Println("It's not equal to 98 or 100") - } -} +package main + +import "fmt" + +func main() { + var num1 int = 100 + + switch num1 { + case 98, 99: + fmt.Println("It's equal to 98") + case 100: + fmt.Println("It's equal to 100") + default: + fmt.Println("It's not equal to 98 or 100") + } +} diff --git a/eBook/examples/chapter_5/switch2.go b/eBook/examples/chapter_5/switch2.go index 80ccae0..42e135b 100644 --- a/eBook/examples/chapter_5/switch2.go +++ b/eBook/examples/chapter_5/switch2.go @@ -1,16 +1,16 @@ -package main - -import "fmt" - -func main() { - var num1 int = 7 - - switch { - case num1 < 0: - fmt.Println("Number is negative") - case num1 > 0 && num1 < 10: - fmt.Println("Number is between 0 and 10") - default: - fmt.Println("Number is 10 or greater") - } -} +package main + +import "fmt" + +func main() { + var num1 int = 7 + + switch { + case num1 < 0: + fmt.Println("Number is negative") + case num1 > 0 && num1 < 10: + fmt.Println("Number is between 0 and 10") + default: + fmt.Println("Number is 10 or greater") + } +} diff --git a/eBook/examples/chapter_6/blank_identifier.go b/eBook/examples/chapter_6/blank_identifier.go index e0a04d0..0ed053c 100644 --- a/eBook/examples/chapter_6/blank_identifier.go +++ b/eBook/examples/chapter_6/blank_identifier.go @@ -1,14 +1,14 @@ -package main - -import "fmt" - -func main() { - var i1 int - var f1 float32 - i1, _, f1 = ThreeValues() - fmt.Printf("The int: %d, the float; %f\n", i1, f1) -} - -func ThreeValues() (int, int, float32) { - return 5, 6, 7.5 -} +package main + +import "fmt" + +func main() { + var i1 int + var f1 float32 + i1, _, f1 = ThreeValues() + fmt.Printf("The int: %d, the float; %f\n", i1, f1) +} + +func ThreeValues() (int, int, float32) { + return 5, 6, 7.5 +} diff --git a/eBook/examples/chapter_6/defer.go b/eBook/examples/chapter_6/defer.go index 61c92c8..317021b 100644 --- a/eBook/examples/chapter_6/defer.go +++ b/eBook/examples/chapter_6/defer.go @@ -1,17 +1,17 @@ -package main - -import "fmt" - -func main() { - Function1() -} - -func Function1() { - fmt.Printf("In Function1 at the top\n") - defer Function2() - fmt.Printf("In Function1 at the bottom!\n") -} - -func Function2() { - fmt.Printf("Function2: Deferred until the end of the calling function!") -} +package main + +import "fmt" + +func main() { + Function1() +} + +func Function1() { + fmt.Printf("In Function1 at the top\n") + defer Function2() + fmt.Printf("In Function1 at the bottom!\n") +} + +func Function2() { + fmt.Printf("Function2: Deferred until the end of the calling function!") +} diff --git a/eBook/examples/chapter_6/defer_dbconn.go b/eBook/examples/chapter_6/defer_dbconn.go index 3898669..4f011f2 100644 --- a/eBook/examples/chapter_6/defer_dbconn.go +++ b/eBook/examples/chapter_6/defer_dbconn.go @@ -1,38 +1,36 @@ -// defer_dbconn.go -package main - -import "fmt" - -func main() { - doDBOperations() -} - -func connectToDB () { - fmt.Println( "ok, connected to db" ) -} - -func disconnectFromDB () { - fmt.Println( "ok, disconnected from db" ) -} - -func doDBOperations() { - connectToDB() - fmt.Println("Defering the database disconnect.") - defer disconnectFromDB() //function called here with defer - fmt.Println("Doing some DB operations ...") - fmt.Println("Oops! some crash or network error ...") - fmt.Println("Returning from function here!") - return //terminate the program - // deferred function executed here just before actually returning, even if there is a return or abnormal termination before -} -/* Output: -ok, connected to db -Defering the database disconnect. -Doing some DB operations ... -Oops! some crash or network error ... -Returning from function here! -ok, disconnected from db -*/ - - - +// defer_dbconn.go +package main + +import "fmt" + +func main() { + doDBOperations() +} + +func connectToDB() { + fmt.Println("ok, connected to db") +} + +func disconnectFromDB() { + fmt.Println("ok, disconnected from db") +} + +func doDBOperations() { + connectToDB() + fmt.Println("Defering the database disconnect.") + defer disconnectFromDB() //function called here with defer + fmt.Println("Doing some DB operations ...") + fmt.Println("Oops! some crash or network error ...") + fmt.Println("Returning from function here!") + return //terminate the program + // deferred function executed here just before actually returning, even if there is a return or abnormal termination before +} + +/* Output: +ok, connected to db +Defering the database disconnect. +Doing some DB operations ... +Oops! some crash or network error ... +Returning from function here! +ok, disconnected from db +*/ diff --git a/eBook/examples/chapter_6/defer_logvalues.go b/eBook/examples/chapter_6/defer_logvalues.go index 73d3874..7144a37 100644 --- a/eBook/examples/chapter_6/defer_logvalues.go +++ b/eBook/examples/chapter_6/defer_logvalues.go @@ -1,19 +1,20 @@ -// defer_logvalues.go -package main - -import ( - "io" - "log" -) - -func func1(s string) (n int, err error) { - defer func() { - log.Printf("func1(%q) = %d, %v", s, n, err) - }() - return 7, io.EOF -} - -func main() { - func1("Go") -} -// Output: 2011/10/04 10:46:11 func1("Go") = 7, EOF \ No newline at end of file +// defer_logvalues.go +package main + +import ( + "io" + "log" +) + +func func1(s string) (n int, err error) { + defer func() { + log.Printf("func1(%q) = %d, %v", s, n, err) + }() + return 7, io.EOF +} + +func main() { + func1("Go") +} + +// Output: 2011/10/04 10:46:11 func1("Go") = 7, EOF diff --git a/eBook/examples/chapter_6/defer_tracing.go b/eBook/examples/chapter_6/defer_tracing.go index b524e41..afa826f 100644 --- a/eBook/examples/chapter_6/defer_tracing.go +++ b/eBook/examples/chapter_6/defer_tracing.go @@ -1,22 +1,22 @@ -package main - -import "fmt" - -func trace(s string) { fmt.Println("entering:", s) } -func untrace(s string) { fmt.Println("leaving:", s) } - -func a() { - trace("a") - defer untrace("a") - fmt.Println("in a") -} - -func b() { - trace("b") - defer untrace("b") - fmt.Println("in b") - a() -} -func main() { - b() -} +package main + +import "fmt" + +func trace(s string) { fmt.Println("entering:", s) } +func untrace(s string) { fmt.Println("leaving:", s) } + +func a() { + trace("a") + defer untrace("a") + fmt.Println("in a") +} + +func b() { + trace("b") + defer untrace("b") + fmt.Println("in b") + a() +} +func main() { + b() +} diff --git a/eBook/examples/chapter_6/defer_tracing2.go b/eBook/examples/chapter_6/defer_tracing2.go index 03972d3..7af27dd 100644 --- a/eBook/examples/chapter_6/defer_tracing2.go +++ b/eBook/examples/chapter_6/defer_tracing2.go @@ -1,25 +1,25 @@ -package main - -import "fmt" - -func trace(s string) string { - fmt.Println("entering:", s) - return s -} -func un(s string) { - fmt.Println("leaving:", s) -} - -func a() { - defer un(trace("a")) - fmt.Println("in a") -} - -func b() { - defer un(trace("b")) - fmt.Println("in b") - a() -} -func main() { - b() -} +package main + +import "fmt" + +func trace(s string) string { + fmt.Println("entering:", s) + return s +} +func un(s string) { + fmt.Println("leaving:", s) +} + +func a() { + defer un(trace("a")) + fmt.Println("in a") +} + +func b() { + defer un(trace("b")) + fmt.Println("in b") + a() +} +func main() { + b() +} diff --git a/eBook/examples/chapter_6/fibonacci.go b/eBook/examples/chapter_6/fibonacci.go index d1f6b0d..473ada8 100644 --- a/eBook/examples/chapter_6/fibonacci.go +++ b/eBook/examples/chapter_6/fibonacci.go @@ -1,56 +1,57 @@ -package main - -import ( - "fmt" - "time" -) - -func main() { - result := 0 - start := time.Now() - for i:=0; i <= 25; i++ { - result = fibonacci(i) - fmt.Printf("fibonacci(%d) is: %d\n", i, result) - } - end := time.Now() - delta := end.Sub(start) - fmt.Printf("longCalculation took this amount of time: %s\n", delta) -} - -func fibonacci(n int) (res int) { - if n <= 1 { - res = 1 - } else { - res = fibonacci(n-1) + fibonacci(n-2) - } - return -} -/* Output: -fibonacci(0) is: 1 -fibonacci(1) is: 1 -fibonacci(2) is: 2 -fibonacci(3) is: 3 -fibonacci(4) is: 5 -fibonacci(5) is: 8 -fibonacci(6) is: 13 -fibonacci(7) is: 21 -fibonacci(8) is: 34 -fibonacci(9) is: 55 -fibonacci(10) is: 89 -fibonacci(11) is: 144 -fibonacci(12) is: 233 -fibonacci(13) is: 377 -fibonacci(14) is: 610 -fibonacci(15) is: 987 -fibonacci(16) is: 1597 -fibonacci(17) is: 2584 -fibonacci(18) is: 4181 -fibonacci(19) is: 6765 -fibonacci(20) is: 10946 -fibonacci(21) is: 17711 -fibonacci(22) is: 28657 -fibonacci(23) is: 46368 -fibonacci(24) is: 75025 -fibonacci(25) is: 121393 -longCalculation took this amount of time: 3.0001ms -*/ +package main + +import ( + "fmt" + "time" +) + +func main() { + result := 0 + start := time.Now() + for i := 0; i <= 25; i++ { + result = fibonacci(i) + fmt.Printf("fibonacci(%d) is: %d\n", i, result) + } + end := time.Now() + delta := end.Sub(start) + fmt.Printf("longCalculation took this amount of time: %s\n", delta) +} + +func fibonacci(n int) (res int) { + if n <= 1 { + res = 1 + } else { + res = fibonacci(n-1) + fibonacci(n-2) + } + return +} + +/* Output: +fibonacci(0) is: 1 +fibonacci(1) is: 1 +fibonacci(2) is: 2 +fibonacci(3) is: 3 +fibonacci(4) is: 5 +fibonacci(5) is: 8 +fibonacci(6) is: 13 +fibonacci(7) is: 21 +fibonacci(8) is: 34 +fibonacci(9) is: 55 +fibonacci(10) is: 89 +fibonacci(11) is: 144 +fibonacci(12) is: 233 +fibonacci(13) is: 377 +fibonacci(14) is: 610 +fibonacci(15) is: 987 +fibonacci(16) is: 1597 +fibonacci(17) is: 2584 +fibonacci(18) is: 4181 +fibonacci(19) is: 6765 +fibonacci(20) is: 10946 +fibonacci(21) is: 17711 +fibonacci(22) is: 28657 +fibonacci(23) is: 46368 +fibonacci(24) is: 75025 +fibonacci(25) is: 121393 +longCalculation took this amount of time: 3.0001ms +*/ diff --git a/eBook/examples/chapter_6/fibonacci_memoization.go b/eBook/examples/chapter_6/fibonacci_memoization.go index 0001de6..56598c9 100644 --- a/eBook/examples/chapter_6/fibonacci_memoization.go +++ b/eBook/examples/chapter_6/fibonacci_memoization.go @@ -1,42 +1,44 @@ -// fibonacci_memoization.go -package main - -import ( - "fmt" - "time" -) - -const LIM = 41 -var fibs [LIM]uint64 - -func main() { - var result uint64 = 0 - start := time.Now() - for i:=0; i < LIM; i++ { - result = fibonacci(i) - fmt.Printf("fibonacci(%d) is: %d\n", i, result) - } - end := time.Now() - delta := end.Sub(start) - fmt.Printf("longCalculation took this amount of time: %s\n", delta) -} - -func fibonacci(n int) (res uint64) { - // memoization: check if fibonacci(n) is already known in array: - if fibs[n] != 0 { - res = fibs[n] - return - } - if n <= 1 { - res = 1 - } else { - res = fibonacci(n-1) + fibonacci(n-2) - } - fibs[n] = res - return -} -/* -Output: LIM=40: -normal (fibonacci.go): the calculation took this amount of time: 4.730270 s - with memoization: the calculation took this amount of time: 0.001000 s -*/ +// fibonacci_memoization.go +package main + +import ( + "fmt" + "time" +) + +const LIM = 41 + +var fibs [LIM]uint64 + +func main() { + var result uint64 = 0 + start := time.Now() + for i := 0; i < LIM; i++ { + result = fibonacci(i) + fmt.Printf("fibonacci(%d) is: %d\n", i, result) + } + end := time.Now() + delta := end.Sub(start) + fmt.Printf("longCalculation took this amount of time: %s\n", delta) +} + +func fibonacci(n int) (res uint64) { + // memoization: check if fibonacci(n) is already known in array: + if fibs[n] != 0 { + res = fibs[n] + return + } + if n <= 1 { + res = 1 + } else { + res = fibonacci(n-1) + fibonacci(n-2) + } + fibs[n] = res + return +} + +/* +Output: LIM=40: +normal (fibonacci.go): the calculation took this amount of time: 4.730270 s + with memoization: the calculation took this amount of time: 0.001000 s +*/ diff --git a/eBook/examples/chapter_6/filter_factory.go b/eBook/examples/chapter_6/filter_factory.go index 13e6788..30206d2 100644 --- a/eBook/examples/chapter_6/filter_factory.go +++ b/eBook/examples/chapter_6/filter_factory.go @@ -1,53 +1,55 @@ -// filter_factory.go -package main -import "fmt" - -type flt func (int) bool -type slice_split func([]int) ([]int, []int) - -func isOdd(integer int) bool{ - if integer%2 == 0 { - return false - } - return true -} - -func isBiggerThan4(integer int) bool{ - if integer > 4 { - return true - } - return false -} - -func filter_factory(f flt) slice_split { - return func(s []int) (yes, no []int){ - for _, val := range s{ - if f(val){ - yes = append(yes, val) - } else { - no = append(no, val) - } - } - return - } -} - -func main(){ - s := []int {1, 2, 3, 4, 5, 7} - fmt.Println("s = ", s) - odd_even_function := filter_factory(isOdd) - odd, even := odd_even_function(s) - fmt.Println("odd = ", odd) - fmt.Println("even = ", even) - //separate those that are bigger than 4 and those that are not. - bigger, smaller := filter_factory(isBiggerThan4)(s) - fmt.Println("Bigger than 4: ", bigger) - fmt.Println("Smaller than or equal to 4: ", smaller) -} -/* -s = [1 2 3 4 5 7] -odd = [1 3 5 7] -even = [2 4] -Bigger than 4: [5 7] -Smaller than or equal to 4: [1 2 3 4] -*/ +// filter_factory.go +package main + +import "fmt" + +type flt func(int) bool +type slice_split func([]int) ([]int, []int) + +func isOdd(integer int) bool { + if integer%2 == 0 { + return false + } + return true +} + +func isBiggerThan4(integer int) bool { + if integer > 4 { + return true + } + return false +} + +func filter_factory(f flt) slice_split { + return func(s []int) (yes, no []int) { + for _, val := range s { + if f(val) { + yes = append(yes, val) + } else { + no = append(no, val) + } + } + return + } +} + +func main() { + s := []int{1, 2, 3, 4, 5, 7} + fmt.Println("s = ", s) + odd_even_function := filter_factory(isOdd) + odd, even := odd_even_function(s) + fmt.Println("odd = ", odd) + fmt.Println("even = ", even) + //separate those that are bigger than 4 and those that are not. + bigger, smaller := filter_factory(isBiggerThan4)(s) + fmt.Println("Bigger than 4: ", bigger) + fmt.Println("Smaller than or equal to 4: ", smaller) +} + +/* +s = [1 2 3 4 5 7] +odd = [1 3 5 7] +even = [2 4] +Bigger than 4: [5 7] +Smaller than or equal to 4: [1 2 3 4] +*/ diff --git a/eBook/examples/chapter_6/function_closure.go b/eBook/examples/chapter_6/function_closure.go index 59104b5..64d2bec 100644 --- a/eBook/examples/chapter_6/function_closure.go +++ b/eBook/examples/chapter_6/function_closure.go @@ -1,18 +1,18 @@ -package main - -import "fmt" - -func main() { - var f = Adder() - fmt.Print(f(1)," - ") - fmt.Print(f(20)," - ") - fmt.Print(f(300)) -} - -func Adder() func(int) int { - var x int - return func(delta int) int { - x += delta - return x - } -} +package main + +import "fmt" + +func main() { + var f = Adder() + fmt.Print(f(1), " - ") + fmt.Print(f(20), " - ") + fmt.Print(f(300)) +} + +func Adder() func(int) int { + var x int + return func(delta int) int { + x += delta + return x + } +} diff --git a/eBook/examples/chapter_6/function_filter.go b/eBook/examples/chapter_6/function_filter.go index fa1a4e7..27f880a 100644 --- a/eBook/examples/chapter_6/function_filter.go +++ b/eBook/examples/chapter_6/function_filter.go @@ -1,48 +1,50 @@ -// function_filter.go -package main -import "fmt" - -type flt func(int) bool - -// isOdd takes an ints and returns a bool set to true if the -// int parameter is odd, or false if not. -// isOdd is of type func(int) bool which is what flt is declared to be. - -func isOdd(n int) bool { - if n%2 == 0 { - return false - } - return true -} - -// Same comment for isEven -func isEven(n int) bool { - if n%2 == 0 { - return true - } - return false -} - -func filter(sl []int, f flt) []int { - var res []int - for _, val := range sl { - if f(val) { - res = append(res, val) - } - } - return res -} - -func main(){ - slice := []int {1, 2, 3, 4, 5, 7} - fmt.Println("slice = ", slice) - odd := filter(slice, isOdd) - fmt.Println("Odd elements of slice are: ", odd) - even := filter(slice, isEven) - fmt.Println("Even elements of slice are: ", even) -} -/* -slice = [1 2 3 4 5 7] -Odd elements of slice are: [1 3 5 7] -Even elements of slice are: [2 4] -*/ +// function_filter.go +package main + +import "fmt" + +type flt func(int) bool + +// isOdd takes an ints and returns a bool set to true if the +// int parameter is odd, or false if not. +// isOdd is of type func(int) bool which is what flt is declared to be. + +func isOdd(n int) bool { + if n%2 == 0 { + return false + } + return true +} + +// Same comment for isEven +func isEven(n int) bool { + if n%2 == 0 { + return true + } + return false +} + +func filter(sl []int, f flt) []int { + var res []int + for _, val := range sl { + if f(val) { + res = append(res, val) + } + } + return res +} + +func main() { + slice := []int{1, 2, 3, 4, 5, 7} + fmt.Println("slice = ", slice) + odd := filter(slice, isOdd) + fmt.Println("Odd elements of slice are: ", odd) + even := filter(slice, isEven) + fmt.Println("Even elements of slice are: ", even) +} + +/* +slice = [1 2 3 4 5 7] +Odd elements of slice are: [1 3 5 7] +Even elements of slice are: [2 4] +*/ diff --git a/eBook/examples/chapter_6/function_literal.go b/eBook/examples/chapter_6/function_literal.go index ece9faf..df9007f 100644 --- a/eBook/examples/chapter_6/function_literal.go +++ b/eBook/examples/chapter_6/function_literal.go @@ -1,15 +1,16 @@ -package main -import "fmt" - -func main() { - f() -} - -func f() { - for i := 0; i < 4; i++ { - g := func(i int) { fmt.Printf("%d ", i) } - g(i) - fmt.Printf(" - g is of type %T and has value %v\n", g, g) - } - -} +package main + +import "fmt" + +func main() { + f() +} + +func f() { + for i := 0; i < 4; i++ { + g := func(i int) { fmt.Printf("%d ", i) } + g(i) + fmt.Printf(" - g is of type %T and has value %v\n", g, g) + } + +} diff --git a/eBook/examples/chapter_6/function_parameter.go b/eBook/examples/chapter_6/function_parameter.go index 3e2fe40..3277a8f 100644 --- a/eBook/examples/chapter_6/function_parameter.go +++ b/eBook/examples/chapter_6/function_parameter.go @@ -1,20 +1,20 @@ -// function_parameter.go -package main - -import ( - "fmt" -) - -func main() { - callback(1, Add) -} - -func Add(a,b int) { - fmt.Printf("The sum of %d and %d is: %d\n", a, b, a + b) -} - - -func callback(y int, f func(int, int)) { - f(y, 2) // this becomes Add(1, 2) -} -// Output: The sum of 1 and 2 is: 3 +// function_parameter.go +package main + +import ( + "fmt" +) + +func main() { + callback(1, Add) +} + +func Add(a, b int) { + fmt.Printf("The sum of %d and %d is: %d\n", a, b, a+b) +} + +func callback(y int, f func(int, int)) { + f(y, 2) // this becomes Add(1, 2) +} + +// Output: The sum of 1 and 2 is: 3 diff --git a/eBook/examples/chapter_6/function_return.go b/eBook/examples/chapter_6/function_return.go index 4d4c72d..b94b5a5 100644 --- a/eBook/examples/chapter_6/function_return.go +++ b/eBook/examples/chapter_6/function_return.go @@ -1,27 +1,29 @@ -package main -import "fmt" - -func main() { - // make an Add2 function, give it a name p2, and call it: - p2 := Add2() - fmt.Printf("Call Add2 for 2 gives: %v\n", p2(2)) - // make a special Adder function, a gets value 2: - TwoAdder := Adder(2) - fmt.Printf("The result is: %v\n", TwoAdder(2)) -} - -func Add2() (func(b int) int) { - return func(b int) int { - return b + 2 - } -} - -func Adder(a int) (func(b int) int) { - return func(b int) int { - return a + b - } -} -/* Output: -Call Add2 for 2 gives: 4 -The result is: 4 -*/ \ No newline at end of file +package main + +import "fmt" + +func main() { + // make an Add2 function, give it a name p2, and call it: + p2 := Add2() + fmt.Printf("Call Add2 for 2 gives: %v\n", p2(2)) + // make a special Adder function, a gets value 2: + TwoAdder := Adder(2) + fmt.Printf("The result is: %v\n", TwoAdder(2)) +} + +func Add2() func(b int) int { + return func(b int) int { + return b + 2 + } +} + +func Adder(a int) func(b int) int { + return func(b int) int { + return a + b + } +} + +/* Output: +Call Add2 for 2 gives: 4 +The result is: 4 +*/ diff --git a/eBook/examples/chapter_6/greeting.go b/eBook/examples/chapter_6/greeting.go index 493a00f..da1ebbe 100644 --- a/eBook/examples/chapter_6/greeting.go +++ b/eBook/examples/chapter_6/greeting.go @@ -1,11 +1,11 @@ -package main - -func main() { - println("In main before calling greeting") - greeting() - println("In main after calling greeting") -} - -func greeting() { - println("In greeting: Hi!!!!!") -} +package main + +func main() { + println("In main before calling greeting") + greeting() + println("In main after calling greeting") +} + +func greeting() { + println("In greeting: Hi!!!!!") +} diff --git a/eBook/examples/chapter_6/minmax.go b/eBook/examples/chapter_6/minmax.go index f0dc134..d47559a 100644 --- a/eBook/examples/chapter_6/minmax.go +++ b/eBook/examples/chapter_6/minmax.go @@ -1,20 +1,20 @@ -package main - -import "fmt" - -func main() { - var min, max int - min, max = MinMax(78, 65) - fmt.Printf("Minimum is: %d, Maximum is: %d\n", min, max) -} - -func MinMax(a int, b int) (min int, max int) { - if a < b { - min = a - max = b - } else { // a = b or a < b - min = b - max = a - } - return -} \ No newline at end of file +package main + +import "fmt" + +func main() { + var min, max int + min, max = MinMax(78, 65) + fmt.Printf("Minimum is: %d, Maximum is: %d\n", min, max) +} + +func MinMax(a int, b int) (min int, max int) { + if a < b { + min = a + max = b + } else { // a = b or a < b + min = b + max = a + } + return +} diff --git a/eBook/examples/chapter_6/multiple_return.go b/eBook/examples/chapter_6/multiple_return.go index 22304d5..2aac2d8 100644 --- a/eBook/examples/chapter_6/multiple_return.go +++ b/eBook/examples/chapter_6/multiple_return.go @@ -1,28 +1,28 @@ -package main - -import "fmt" - -var num int = 10 -var numx2, numx3 int - -func main() { - numx2, numx3 = getX2AndX3(num) - PrintValues() - numx2, numx3 = getX2AndX3_2(num) - PrintValues() -} - -func PrintValues() { - fmt.Printf("num = %d, 2x num = %d, 3x num = %d\n", num, numx2, numx3) -} - -func getX2AndX3(input int) (int, int) { - return 2 * input, 3 * input -} - -func getX2AndX3_2(input int) (x2 int, x3 int) { - x2 = 2 * input - x3 = 3 * input - // return x2, x3 - return -} +package main + +import "fmt" + +var num int = 10 +var numx2, numx3 int + +func main() { + numx2, numx3 = getX2AndX3(num) + PrintValues() + numx2, numx3 = getX2AndX3_2(num) + PrintValues() +} + +func PrintValues() { + fmt.Printf("num = %d, 2x num = %d, 3x num = %d\n", num, numx2, numx3) +} + +func getX2AndX3(input int) (int, int) { + return 2 * input, 3 * input +} + +func getX2AndX3_2(input int) (x2 int, x3 int) { + x2 = 2 * input + x3 = 3 * input + // return x2, x3 + return +} diff --git a/eBook/examples/chapter_6/mut_recurs.go b/eBook/examples/chapter_6/mut_recurs.go index cc9a8f4..62c340d 100644 --- a/eBook/examples/chapter_6/mut_recurs.go +++ b/eBook/examples/chapter_6/mut_recurs.go @@ -1,27 +1,33 @@ -// mut_recurs.go -package main - -import ( - "fmt" -) - -func main() { - fmt.Printf("%d is even: is %t\n", 16, even(16)) // 16 is even: is true - fmt.Printf("%d is odd: is %t\n", 17, odd(17)) // 17 is odd: is true - fmt.Printf("%d is odd: is %t\n", 18, odd(18)) // 18 is odd: is false -} - -func even(nr int) bool { - if nr == 0 {return true} - return odd(RevSign(nr)-1) -} - -func odd(nr int) bool { - if nr == 0 {return false} - return even(RevSign(nr)-1) -} - -func RevSign(nr int) int { - if nr < 0 {return -nr} - return nr -} \ No newline at end of file +// mut_recurs.go +package main + +import ( + "fmt" +) + +func main() { + fmt.Printf("%d is even: is %t\n", 16, even(16)) // 16 is even: is true + fmt.Printf("%d is odd: is %t\n", 17, odd(17)) // 17 is odd: is true + fmt.Printf("%d is odd: is %t\n", 18, odd(18)) // 18 is odd: is false +} + +func even(nr int) bool { + if nr == 0 { + return true + } + return odd(RevSign(nr) - 1) +} + +func odd(nr int) bool { + if nr == 0 { + return false + } + return even(RevSign(nr) - 1) +} + +func RevSign(nr int) int { + if nr < 0 { + return -nr + } + return nr +} diff --git a/eBook/examples/chapter_6/return_defer.go b/eBook/examples/chapter_6/return_defer.go index b6a82c7..dcfdf75 100644 --- a/eBook/examples/chapter_6/return_defer.go +++ b/eBook/examples/chapter_6/return_defer.go @@ -1,18 +1,19 @@ -// test_defer.go -package main - -import ( - "fmt" -) - -func f() (ret int) { - defer func() { - ret++ - }() - return 1 -} - -func main() { - fmt.Println(f()) -} -// Output: 2 +// test_defer.go +package main + +import ( + "fmt" +) + +func f() (ret int) { + defer func() { + ret++ + }() + return 1 +} + +func main() { + fmt.Println(f()) +} + +// Output: 2 diff --git a/eBook/examples/chapter_6/side_effect.go b/eBook/examples/chapter_6/side_effect.go index 7c7c055..d4b2b77 100644 --- a/eBook/examples/chapter_6/side_effect.go +++ b/eBook/examples/chapter_6/side_effect.go @@ -1,18 +1,18 @@ -// side_effect.go -package main - -import ( - "fmt" -) - -func Multiply(a, b int, reply *int) { - *reply = a * b -} - -func main() { - n := 0 - reply := &n - Multiply(10, 5, reply) - fmt.Println("Multiply:", *reply) // Multiply: 50 - fmt.Println("Multiply:", n) // Multiply: 50 -} +// side_effect.go +package main + +import ( + "fmt" +) + +func Multiply(a, b int, reply *int) { + *reply = a * b +} + +func main() { + n := 0 + reply := &n + Multiply(10, 5, reply) + fmt.Println("Multiply:", *reply) // Multiply: 50 + fmt.Println("Multiply:", n) // Multiply: 50 +} diff --git a/eBook/examples/chapter_6/simple_function.go b/eBook/examples/chapter_6/simple_function.go index 3318f96..d70db0c 100644 --- a/eBook/examples/chapter_6/simple_function.go +++ b/eBook/examples/chapter_6/simple_function.go @@ -1,15 +1,15 @@ -package main - -import "fmt" - -func main() { - var i1 int = MultiPly3Nums(2, 5, 6) - fmt.Printf("Multiply 2 * 5 * 6 = %d\n", i1) - // fmt.Printf("Multiply 2 * 5 * 6 = %d\n", MultiPly3Nums(2, 5, 6)) -} - -func MultiPly3Nums(a int, b int, c int) int { - // var product int = a * b * c - // return product - return a * b * c -} +package main + +import "fmt" + +func main() { + var i1 int = MultiPly3Nums(2, 5, 6) + fmt.Printf("Multiply 2 * 5 * 6 = %d\n", i1) + // fmt.Printf("Multiply 2 * 5 * 6 = %d\n", MultiPly3Nums(2, 5, 6)) +} + +func MultiPly3Nums(a int, b int, c int) int { + // var product int = a * b * c + // return product + return a * b * c +} diff --git a/eBook/examples/chapter_6/varnumpar.go b/eBook/examples/chapter_6/varnumpar.go index 2e78470..c374956 100644 --- a/eBook/examples/chapter_6/varnumpar.go +++ b/eBook/examples/chapter_6/varnumpar.go @@ -1,28 +1,29 @@ -package main - -import "fmt" - -func main() { - x := Min(1, 3, 2, 0) - fmt.Printf("The minimum is: %d\n", x) - arr := []int{7,9,3,5,1} - x = Min(arr...) - fmt.Printf("The minimum in the array arr is: %d", x) -} - -func Min(a ...int) int { - if len(a)==0 { - return 0 - } - min := a[0] - for _, v := range a { - if v < min { - min = v - } - } - return min -} -/* -The minimum is: 0 -The minimum in the array arr is: 1 -*/ \ No newline at end of file +package main + +import "fmt" + +func main() { + x := Min(1, 3, 2, 0) + fmt.Printf("The minimum is: %d\n", x) + arr := []int{7, 9, 3, 5, 1} + x = Min(arr...) + fmt.Printf("The minimum in the array arr is: %d", x) +} + +func Min(a ...int) int { + if len(a) == 0 { + return 0 + } + min := a[0] + for _, v := range a { + if v < min { + min = v + } + } + return min +} + +/* +The minimum is: 0 +The minimum in the array arr is: 1 +*/ diff --git a/eBook/examples/chapter_7/array_literals.go b/eBook/examples/chapter_7/array_literals.go index 63e8997..4bf0467 100644 --- a/eBook/examples/chapter_7/array_literals.go +++ b/eBook/examples/chapter_7/array_literals.go @@ -1,24 +1,24 @@ -package main - -import "fmt" - -func main() { - var arrAge = [5]int{18, 20, 15, 22, 16} - var arrLazy = [...]int{5, 6, 7, 8, 22} - // var arrLazy = []int{5, 6, 7, 8, 22} - var arrKeyValue = [5]string{3: "Chris", 4: "Ron"} - //var arrKeyValue = []string{3: "Chris", 4: "Ron"} - for i := 0; i < len(arrAge); i++ { - fmt.Printf("Age at %d is %d\n", i, arrAge[i]) - } - fmt.Println() - - for i := 0; i < len(arrLazy); i++ { - fmt.Printf("Number at %d is %d\n", i, arrLazy[i]) - } - fmt.Printf("\n") - - for i := 0; i < len(arrKeyValue); i++ { - fmt.Printf("Person at %d is %s\n", i, arrKeyValue[i]) - } -} +package main + +import "fmt" + +func main() { + var arrAge = [5]int{18, 20, 15, 22, 16} + var arrLazy = [...]int{5, 6, 7, 8, 22} + // var arrLazy = []int{5, 6, 7, 8, 22} + var arrKeyValue = [5]string{3: "Chris", 4: "Ron"} + //var arrKeyValue = []string{3: "Chris", 4: "Ron"} + for i := 0; i < len(arrAge); i++ { + fmt.Printf("Age at %d is %d\n", i, arrAge[i]) + } + fmt.Println() + + for i := 0; i < len(arrLazy); i++ { + fmt.Printf("Number at %d is %d\n", i, arrLazy[i]) + } + fmt.Printf("\n") + + for i := 0; i < len(arrKeyValue); i++ { + fmt.Printf("Person at %d is %s\n", i, arrKeyValue[i]) + } +} diff --git a/eBook/examples/chapter_7/array_slices.go b/eBook/examples/chapter_7/array_slices.go index 9b1bf12..b8be0e3 100644 --- a/eBook/examples/chapter_7/array_slices.go +++ b/eBook/examples/chapter_7/array_slices.go @@ -1,33 +1,33 @@ -package main - -import "fmt" - -func main() { - var arr1 [6]int - var slice1 []int = arr1[2:5] // index 5 niet meegerekend! - - // load the array with integers: 0,1,2,3,4,5 - for i := 0; i < len(arr1); i++ { - arr1[i] = i - } - - // print the slice: - for i := 0; i < len(slice1); i++ { - fmt.Printf("Slice at %d is %d\n", i, slice1[i]) - } - - fmt.Printf("The length of arr1 is %d\n", len(arr1)) - fmt.Printf("The length of slice1 is %d\n", len(slice1)) - fmt.Printf("The capacity of slice1 is %d\n", cap(slice1)) - - // grow the slice: - slice1 = slice1[0:4] - for i := 0; i < len(slice1); i++ { - fmt.Printf("Slice at %d is %d\n", i, slice1[i]) - } - fmt.Printf("The length of slice1 is %d\n", len(slice1)) - fmt.Printf("The capacity of slice1 is %d\n", cap(slice1)) - - // grow the slice beyond capacity: - // slice1 = slice1[0:7 ] // panic: runtime error: slice bounds out of range -} +package main + +import "fmt" + +func main() { + var arr1 [6]int + var slice1 []int = arr1[2:5] // index 5 niet meegerekend! + + // load the array with integers: 0,1,2,3,4,5 + for i := 0; i < len(arr1); i++ { + arr1[i] = i + } + + // print the slice: + for i := 0; i < len(slice1); i++ { + fmt.Printf("Slice at %d is %d\n", i, slice1[i]) + } + + fmt.Printf("The length of arr1 is %d\n", len(arr1)) + fmt.Printf("The length of slice1 is %d\n", len(slice1)) + fmt.Printf("The capacity of slice1 is %d\n", cap(slice1)) + + // grow the slice: + slice1 = slice1[0:4] + for i := 0; i < len(slice1); i++ { + fmt.Printf("Slice at %d is %d\n", i, slice1[i]) + } + fmt.Printf("The length of slice1 is %d\n", len(slice1)) + fmt.Printf("The capacity of slice1 is %d\n", cap(slice1)) + + // grow the slice beyond capacity: + // slice1 = slice1[0:7 ] // panic: runtime error: slice bounds out of range +} diff --git a/eBook/examples/chapter_7/array_sum.go b/eBook/examples/chapter_7/array_sum.go index 2f33720..ee2d096 100644 --- a/eBook/examples/chapter_7/array_sum.go +++ b/eBook/examples/chapter_7/array_sum.go @@ -1,17 +1,18 @@ -package main - -import "fmt" - -func main() { - array := [3]float64{7.0, 8.5, 9.1} - x := Sum(&array) // Note the explicit address-of operator to pass a pointer to the array - fmt.Printf("The sum of the array is: %f", x) -} - -func Sum(a *[3]float64) (sum float64) { - for _, v := range a { // can also with dereferencing *a to get back to the array - sum += v - } - return -} -// Output: The sum of the array is: 24.600000 +package main + +import "fmt" + +func main() { + array := [3]float64{7.0, 8.5, 9.1} + x := Sum(&array) // Note the explicit address-of operator to pass a pointer to the array + fmt.Printf("The sum of the array is: %f", x) +} + +func Sum(a *[3]float64) (sum float64) { + for _, v := range a { // can also with dereferencing *a to get back to the array + sum += v + } + return +} + +// Output: The sum of the array is: 24.600000 diff --git a/eBook/examples/chapter_7/copy_append_slice.go b/eBook/examples/chapter_7/copy_append_slice.go index f9cb3b6..a26e22d 100644 --- a/eBook/examples/chapter_7/copy_append_slice.go +++ b/eBook/examples/chapter_7/copy_append_slice.go @@ -1,16 +1,16 @@ -package main - -import "fmt" - -func main() { - sl_from := []int{1,2,3} - sl_to := make([]int,10) - - n := copy(sl_to, sl_from) - fmt.Println(sl_to) // output: [1 2 3 0 0 0 0 0 0 0] - fmt.Printf("Copied %d elements\n", n) // n == 3 - - sl3 := []int{1,2,3} - sl3 = append(sl3, 4, 5, 6) - fmt.Println(sl3) // output: [1 2 3 4 5 6] -} +package main + +import "fmt" + +func main() { + sl_from := []int{1, 2, 3} + sl_to := make([]int, 10) + + n := copy(sl_to, sl_from) + fmt.Println(sl_to) // output: [1 2 3 0 0 0 0 0 0 0] + fmt.Printf("Copied %d elements\n", n) // n == 3 + + sl3 := []int{1, 2, 3} + sl3 = append(sl3, 4, 5, 6) + fmt.Println(sl3) // output: [1 2 3 4 5 6] +} diff --git a/eBook/examples/chapter_7/for_arrays.go b/eBook/examples/chapter_7/for_arrays.go index f7182aa..47f1677 100644 --- a/eBook/examples/chapter_7/for_arrays.go +++ b/eBook/examples/chapter_7/for_arrays.go @@ -1,16 +1,16 @@ -package main - -import "fmt" - -func main() { - var arr1 [5]int - // var arr1 = new([5]int) - - for i:=0; i < len(arr1); i++ { - arr1[i] = i * 2 - } - - for i:=0; i < len(arr1); i++ { - fmt.Printf("Array at index %d is %d\n", i, arr1[i]) - } -} \ No newline at end of file +package main + +import "fmt" + +func main() { + var arr1 [5]int + // var arr1 = new([5]int) + + for i := 0; i < len(arr1); i++ { + arr1[i] = i * 2 + } + + for i := 0; i < len(arr1); i++ { + fmt.Printf("Array at index %d is %d\n", i, arr1[i]) + } +} diff --git a/eBook/examples/chapter_7/for_string.go b/eBook/examples/chapter_7/for_string.go index 23cfb7b..0446003 100644 --- a/eBook/examples/chapter_7/for_string.go +++ b/eBook/examples/chapter_7/for_string.go @@ -1,11 +1,12 @@ -package main - -import "fmt" - -func main() { - s := "\u00ff\u754c" - for i, c := range s { - fmt.Printf("%d:%c ", i, c) - } -} -// prints: 0:ÿ 2:界 \ No newline at end of file +package main + +import "fmt" + +func main() { + s := "\u00ff\u754c" + for i, c := range s { + fmt.Printf("%d:%c ", i, c) + } +} + +// prints: 0:ÿ 2:界 diff --git a/eBook/examples/chapter_7/make_slice.go b/eBook/examples/chapter_7/make_slice.go index 321e535..d102304 100644 --- a/eBook/examples/chapter_7/make_slice.go +++ b/eBook/examples/chapter_7/make_slice.go @@ -1,18 +1,18 @@ -package main - -import "fmt" - -func main() { - // var slice1 []int = make([]int, 10) - slice1 := make([]int, 10) - // load the array/slice: - for i := 0; i < len(slice1); i++ { - slice1[i] = 5 * i - } - // print the slice: - for i := 0; i < len(slice1); i++ { - fmt.Printf("Slice at %d is %d\n", i, slice1[i]) - } - fmt.Printf("\nThe length of slice1 is %d\n", len(slice1)) - fmt.Printf("The capacity of slice1 is %d\n", cap(slice1)) -} +package main + +import "fmt" + +func main() { + // var slice1 []int = make([]int, 10) + slice1 := make([]int, 10) + // load the array/slice: + for i := 0; i < len(slice1); i++ { + slice1[i] = 5 * i + } + // print the slice: + for i := 0; i < len(slice1); i++ { + fmt.Printf("Slice at %d is %d\n", i, slice1[i]) + } + fmt.Printf("\nThe length of slice1 is %d\n", len(slice1)) + fmt.Printf("The capacity of slice1 is %d\n", cap(slice1)) +} diff --git a/eBook/examples/chapter_7/multidim_array.go b/eBook/examples/chapter_7/multidim_array.go index b73d732..4f1ce7f 100644 --- a/eBook/examples/chapter_7/multidim_array.go +++ b/eBook/examples/chapter_7/multidim_array.go @@ -1,35 +1,37 @@ -// multidim_array.go -package main - -import "fmt" - -const ( - WIDTH = 1920 - HEIGHT = 1080 - // WIDTH = 5 - // HEIGHT = 4 -) - -type pixel int -var screen [WIDTH][HEIGHT]pixel - -func main() { - for y := 0; y < HEIGHT; y++ { - for x := 0; x < WIDTH; x++ { - screen[x][y] = 0 - } - } - fmt.Println(screen) - - for row := range screen { - for column := range screen[0] { - screen[row][column] = 1 - } - } - - fmt.Println(screen) -} -/* Output for WIDTH = 5 and HEIGHT = 4: -[[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] -[[1 1 1 1] [1 1 1 1] [1 1 1 1] [1 1 1 1] [1 1 1 1]] -*/ +// multidim_array.go +package main + +import "fmt" + +const ( + WIDTH = 1920 + HEIGHT = 1080 + // WIDTH = 5 + // HEIGHT = 4 +) + +type pixel int + +var screen [WIDTH][HEIGHT]pixel + +func main() { + for y := 0; y < HEIGHT; y++ { + for x := 0; x < WIDTH; x++ { + screen[x][y] = 0 + } + } + fmt.Println(screen) + + for row := range screen { + for column := range screen[0] { + screen[row][column] = 1 + } + } + + fmt.Println(screen) +} + +/* Output for WIDTH = 5 and HEIGHT = 4: +[[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] +[[1 1 1 1] [1 1 1 1] [1 1 1 1] [1 1 1 1] [1 1 1 1]] +*/ diff --git a/eBook/examples/chapter_7/pointer_array.go b/eBook/examples/chapter_7/pointer_array.go index 2cd1487..01c96de 100644 --- a/eBook/examples/chapter_7/pointer_array.go +++ b/eBook/examples/chapter_7/pointer_array.go @@ -1,12 +1,12 @@ -package main - -import "fmt" - -func f(a [3]int) { fmt.Println(a) } -func fp(a *[3]int) { fmt.Println(a) } - -func main() { - var ar [3]int - f(ar) // passes a copy of ar - fp(&ar) // passes a pointer to ar -} +package main + +import "fmt" + +func f(a [3]int) { fmt.Println(a) } +func fp(a *[3]int) { fmt.Println(a) } + +func main() { + var ar [3]int + f(ar) // passes a copy of ar + fp(&ar) // passes a pointer to ar +} diff --git a/eBook/examples/chapter_7/pointer_array2.go b/eBook/examples/chapter_7/pointer_array2.go index 4816f89..505d910 100644 --- a/eBook/examples/chapter_7/pointer_array2.go +++ b/eBook/examples/chapter_7/pointer_array2.go @@ -1,11 +1,11 @@ -package main - -import "fmt" - -func fp(a *[3]int) { fmt.Println(a) } - -func main() { - for i := 0; i < 3; i++ { - fp(&[3]int{i, i * i, i * i * i}) - } -} +package main + +import "fmt" + +func fp(a *[3]int) { fmt.Println(a) } + +func main() { + for i := 0; i < 3; i++ { + fp(&[3]int{i, i * i, i * i * i}) + } +} diff --git a/eBook/examples/chapter_7/reslicing.go b/eBook/examples/chapter_7/reslicing.go index a34a4e0..b12c237 100644 --- a/eBook/examples/chapter_7/reslicing.go +++ b/eBook/examples/chapter_7/reslicing.go @@ -1,18 +1,18 @@ -package main - -import "fmt" - -func main() { - //var slice1 []int = make([]int, 0, 10) - slice1 := make([]int, 0, 10) - // load the slice, cap(slice1) is 10: - for i := 0; i < cap(slice1); i++ { - slice1 = slice1[0:i+1] // reslice - slice1[i] = i - fmt.Printf("The length of slice is %d\n", len(slice1)) - } - // print the slice: - for i := 0; i < len(slice1); i++ { - fmt.Printf("Slice at %d is %d\n", i, slice1[i]) - } -} +package main + +import "fmt" + +func main() { + //var slice1 []int = make([]int, 0, 10) + slice1 := make([]int, 0, 10) + // load the slice, cap(slice1) is 10: + for i := 0; i < cap(slice1); i++ { + slice1 = slice1[0 : i+1] // reslice + slice1[i] = i + fmt.Printf("The length of slice is %d\n", len(slice1)) + } + // print the slice: + for i := 0; i < len(slice1); i++ { + fmt.Printf("Slice at %d is %d\n", i, slice1[i]) + } +} diff --git a/eBook/examples/chapter_7/slices_forrange.go b/eBook/examples/chapter_7/slices_forrange.go index 6ffb374..22f745a 100644 --- a/eBook/examples/chapter_7/slices_forrange.go +++ b/eBook/examples/chapter_7/slices_forrange.go @@ -1,22 +1,23 @@ -package main - -import "fmt" - -func main() { - var slice1 []int = make([]int, 4) - - slice1[0] = 1 - slice1[1] = 2 - slice1[2] = 3 - slice1[3] = 4 - - for ix, value := range slice1 { - fmt.Printf("Slice at %d is: %d\n", ix, value) - } -} -/* -Slice at 0 is: 1 -Slice at 1 is: 2 -Slice at 2 is: 3 -Slice at 3 is: 4 -*/ +package main + +import "fmt" + +func main() { + var slice1 []int = make([]int, 4) + + slice1[0] = 1 + slice1[1] = 2 + slice1[2] = 3 + slice1[3] = 4 + + for ix, value := range slice1 { + fmt.Printf("Slice at %d is: %d\n", ix, value) + } +} + +/* +Slice at 0 is: 1 +Slice at 1 is: 2 +Slice at 2 is: 3 +Slice at 3 is: 4 +*/ diff --git a/eBook/examples/chapter_7/slices_forrange2.go b/eBook/examples/chapter_7/slices_forrange2.go index 365573e..d58d410 100644 --- a/eBook/examples/chapter_7/slices_forrange2.go +++ b/eBook/examples/chapter_7/slices_forrange2.go @@ -1,31 +1,32 @@ -package main - -import "fmt" - -func main() { - seasons := []string{"Spring","Summer","Autumn","Winter"} - - for ix, season := range seasons { - fmt.Printf("Season %d is: %s\n", ix, season) - } - - var season string - for _, season = range seasons { - fmt.Printf("%s\n", season) - } - - for ix := range seasons { - fmt.Printf("%d ", ix) - } -} -/* Output: -Season 0 is: Spring -Season 1 is: Summer -Season 2 is: Autumn -Season 3 is: Winter -Spring -Summer -Autumn -Winter -0 1 2 3 -*/ +package main + +import "fmt" + +func main() { + seasons := []string{"Spring", "Summer", "Autumn", "Winter"} + + for ix, season := range seasons { + fmt.Printf("Season %d is: %s\n", ix, season) + } + + var season string + for _, season = range seasons { + fmt.Printf("%s\n", season) + } + + for ix := range seasons { + fmt.Printf("%d ", ix) + } +} + +/* Output: +Season 0 is: Spring +Season 1 is: Summer +Season 2 is: Autumn +Season 3 is: Winter +Spring +Summer +Autumn +Winter +0 1 2 3 +*/ diff --git a/eBook/examples/chapter_8/invert_map.go b/eBook/examples/chapter_8/invert_map.go index 12eab02..da71c6e 100644 --- a/eBook/examples/chapter_8/invert_map.go +++ b/eBook/examples/chapter_8/invert_map.go @@ -1,29 +1,29 @@ -// invert_map.go -package main - -import ( - "fmt" -) - -var ( - barVal = map[string]int{"alpha": 34, "bravo": 56, "charlie": 23, "delta": 87, - "echo": 56, "foxtrot": 12, "golf": 34, "hotel": 16, "indio": 87, "juliet": 65, "kilo": 43, "lima": 98} -) - -func main() { - invMap := make(map[int]string, len(barVal)) - for k, v := range barVal { - invMap[v] = k - } - fmt.Println("inverted:") - for k, v := range invMap { - fmt.Printf("Key: %v, Value: %v / ", k, v) - } -} -/* Output: -inverted: -Key: 12, Value: foxtrot / Key: 16, Value: hotel / Key: 87, Value: delta / Key: 23, Value: charlie / -Key: 65, Value: juliet / Key: 43, Value: kilo / Key: 56, Value: bravo / Key: 98, Value: lima / -Key: 34, Value: golf / -*/ - +// invert_map.go +package main + +import ( + "fmt" +) + +var ( + barVal = map[string]int{"alpha": 34, "bravo": 56, "charlie": 23, "delta": 87, + "echo": 56, "foxtrot": 12, "golf": 34, "hotel": 16, "indio": 87, "juliet": 65, "kilo": 43, "lima": 98} +) + +func main() { + invMap := make(map[int]string, len(barVal)) + for k, v := range barVal { + invMap[v] = k + } + fmt.Println("inverted:") + for k, v := range invMap { + fmt.Printf("Key: %v, Value: %v / ", k, v) + } +} + +/* Output: +inverted: +Key: 12, Value: foxtrot / Key: 16, Value: hotel / Key: 87, Value: delta / Key: 23, Value: charlie / +Key: 65, Value: juliet / Key: 43, Value: kilo / Key: 56, Value: bravo / Key: 98, Value: lima / +Key: 34, Value: golf / +*/ diff --git a/eBook/examples/chapter_8/make_maps.go b/eBook/examples/chapter_8/make_maps.go index f5eec5e..84b215b 100644 --- a/eBook/examples/chapter_8/make_maps.go +++ b/eBook/examples/chapter_8/make_maps.go @@ -20,6 +20,7 @@ func main() { fmt.Printf("Map assigned at \"two\" is: %d\n", mapLit["two"]) fmt.Printf("Map literal at \"ten\" is: %d\n", mapLit["ten"]) } + /* Output: Map literal at "one" is: 1 Map created at "key2" is: 3.141590 diff --git a/eBook/examples/chapter_8/map_func.go b/eBook/examples/chapter_8/map_func.go index c1fe4a2..5ae5b03 100644 --- a/eBook/examples/chapter_8/map_func.go +++ b/eBook/examples/chapter_8/map_func.go @@ -1,13 +1,15 @@ -// map_func.go -package main -import "fmt" - -func main() { - mf := map[int]func() int{ - 1: func() int { return 10 }, - 2: func() int { return 20 }, - 5: func() int { return 50 }, - } - fmt.Println(mf) -} -// Output: map[1:0x10903be0 5:0x10903ba0 2:0x10903bc0] +// map_func.go +package main + +import "fmt" + +func main() { + mf := map[int]func() int{ + 1: func() int { return 10 }, + 2: func() int { return 20 }, + 5: func() int { return 50 }, + } + fmt.Println(mf) +} + +// Output: map[1:0x10903be0 5:0x10903ba0 2:0x10903bc0] diff --git a/eBook/examples/chapter_8/map_testelement.go b/eBook/examples/chapter_8/map_testelement.go index 35ff35b..49f8aea 100644 --- a/eBook/examples/chapter_8/map_testelement.go +++ b/eBook/examples/chapter_8/map_testelement.go @@ -1,33 +1,33 @@ -package main - -import "fmt" - -func main() { - var value int - var isPresent bool - - map1 := make(map[string]int) - map1["New Delhi"] = 55 - map1["Bejing"] = 20 - map1["Washington"] = 25 - - value, isPresent = map1["Bejing"] - if isPresent { - fmt.Printf("The value of \"Bejing\" in map1 is: %d\n", value) - } else { - fmt.Println("map1 does not contain Bejing") - } - - value, isPresent = map1["Paris"] - fmt.Printf("Is \"Paris\" in map1 ?: %t\n", isPresent) - fmt.Printf("Value is: %d\n", value) - - // delete an item: - delete(map1, "Washington") - value, isPresent = map1["Washington"] - if isPresent { - fmt.Printf("The value of \"Washington\" in map1 is: %d\n", value) - } else { - fmt.Println("map1 does not contain Washington") - } -} +package main + +import "fmt" + +func main() { + var value int + var isPresent bool + + map1 := make(map[string]int) + map1["New Delhi"] = 55 + map1["Bejing"] = 20 + map1["Washington"] = 25 + + value, isPresent = map1["Bejing"] + if isPresent { + fmt.Printf("The value of \"Bejing\" in map1 is: %d\n", value) + } else { + fmt.Println("map1 does not contain Bejing") + } + + value, isPresent = map1["Paris"] + fmt.Printf("Is \"Paris\" in map1 ?: %t\n", isPresent) + fmt.Printf("Value is: %d\n", value) + + // delete an item: + delete(map1, "Washington") + value, isPresent = map1["Washington"] + if isPresent { + fmt.Printf("The value of \"Washington\" in map1 is: %d\n", value) + } else { + fmt.Println("map1 does not contain Washington") + } +} diff --git a/eBook/examples/chapter_8/maps_forrange.go b/eBook/examples/chapter_8/maps_forrange.go index 8a2b84e..a60eab8 100644 --- a/eBook/examples/chapter_8/maps_forrange.go +++ b/eBook/examples/chapter_8/maps_forrange.go @@ -1,15 +1,15 @@ -package main - -import "fmt" - -func main() { - map1 := make(map[int]float32) - map1[1] = 1.0 - map1[2] = 2.0 - map1[3] = 3.0 - map1[4] = 4.0 - - for key, value := range map1 { - fmt.Printf("key is: %d - value is: %f\n", key, value) - } -} +package main + +import "fmt" + +func main() { + map1 := make(map[int]float32) + map1[1] = 1.0 + map1[2] = 2.0 + map1[3] = 3.0 + map1[4] = 4.0 + + for key, value := range map1 { + fmt.Printf("key is: %d - value is: %f\n", key, value) + } +} diff --git a/eBook/examples/chapter_8/slice_maps.go b/eBook/examples/chapter_8/slice_maps.go index ccc17e8..9e25bfc 100644 --- a/eBook/examples/chapter_8/slice_maps.go +++ b/eBook/examples/chapter_8/slice_maps.go @@ -1,27 +1,28 @@ -// slice_maps.go -package main - -import ( - "fmt" -) - -func main() { -// Version A: - items := make([]map[int]int, 5) - for i := range items { - items[i] = make(map[int]int, 1) - items[i][1] = 2 - } - fmt.Printf("Version A: Value of items: %v\n", items) -// Version B: - items2 := make([]map[int]int, 5) - for _, item := range items2 { - item = make(map[int]int, 1) // item is only a copy of the slice element. - item[1] = 2 // This 'item' will be lost on the next iteration. - } - fmt.Printf("Version B: Value of items: %v\n", items2) -} -/* Output: -Version A: Value of items: [map[1:2] map[1:2] map[1:2] map[1:2] map[1:2]] -Version B: Value of items: [map[] map[] map[] map[] map[]] -*/ +// slice_maps.go +package main + +import ( + "fmt" +) + +func main() { + // Version A: + items := make([]map[int]int, 5) + for i := range items { + items[i] = make(map[int]int, 1) + items[i][1] = 2 + } + fmt.Printf("Version A: Value of items: %v\n", items) + // Version B: + items2 := make([]map[int]int, 5) + for _, item := range items2 { + item = make(map[int]int, 1) // item is only a copy of the slice element. + item[1] = 2 // This 'item' will be lost on the next iteration. + } + fmt.Printf("Version B: Value of items: %v\n", items2) +} + +/* Output: +Version A: Value of items: [map[1:2] map[1:2] map[1:2] map[1:2] map[1:2]] +Version B: Value of items: [map[] map[] map[] map[] map[]] +*/ diff --git a/eBook/examples/chapter_8/sort_map.go b/eBook/examples/chapter_8/sort_map.go index 976c5a8..00bd1af 100644 --- a/eBook/examples/chapter_8/sort_map.go +++ b/eBook/examples/chapter_8/sort_map.go @@ -1,43 +1,43 @@ -// sort_map.go -// the telephone alphabet: -package main - -import ( - "fmt" - "sort" -) - -var ( - barVal = map[string]int{"alpha": 34, "bravo": 56, "charlie": 23, "delta": 87, - "echo": 56, "foxtrot": 12, "golf": 34, "hotel": 16, "indio": 87, "juliet": 65, "kilo": 43, "lima": 98} -) - -func main() { - fmt.Println("unsorted:") - for k, v := range barVal { - fmt.Printf("Key: %v, Value: %v / ", k, v) - } - keys := make([]string, len(barVal)) - i := 0 - for k, _ := range barVal { - keys[i] = k - i++ - } - sort.Strings(keys) - fmt.Println() - fmt.Println("sorted:") - for _, k := range keys { - fmt.Printf("Key: %v, Value: %v / ", k, barVal[k]) - } -} -/* Output: -unsorted: -Key: indio, Value: 87 / Key: echo, Value: 56 / Key: juliet, Value: 65 / Key: charlie, Value: 23 / -Key: hotel, Value: 16 / Key: lima, Value: 98 / Key: bravo, Value: 56 / Key: alpha, Value: 34 / -Key: kilo, Value: 43 / Key: delta, Value: 87 / Key: golf, Value: 34 / Key: foxtrot, Value: 12 / -sorted: -Key: alpha, Value: 34 / Key: bravo, Value: 56 / Key: charlie, Value: 23 / Key: delta, Value: 87 / -Key: echo, Value: 56 / Key: foxtrot, Value: 12 / Key: golf, Value: 34 / Key: hotel, Value: 16 / -Key: indio, Value: 87 / Key: juliet, Value: 65 / Key: kilo, Value: 43 / Key: lima, Value: 98 / -*/ - +// sort_map.go +// the telephone alphabet: +package main + +import ( + "fmt" + "sort" +) + +var ( + barVal = map[string]int{"alpha": 34, "bravo": 56, "charlie": 23, "delta": 87, + "echo": 56, "foxtrot": 12, "golf": 34, "hotel": 16, "indio": 87, "juliet": 65, "kilo": 43, "lima": 98} +) + +func main() { + fmt.Println("unsorted:") + for k, v := range barVal { + fmt.Printf("Key: %v, Value: %v / ", k, v) + } + keys := make([]string, len(barVal)) + i := 0 + for k := range barVal { + keys[i] = k + i++ + } + sort.Strings(keys) + fmt.Println() + fmt.Println("sorted:") + for _, k := range keys { + fmt.Printf("Key: %v, Value: %v / ", k, barVal[k]) + } +} + +/* Output: +unsorted: +Key: indio, Value: 87 / Key: echo, Value: 56 / Key: juliet, Value: 65 / Key: charlie, Value: 23 / +Key: hotel, Value: 16 / Key: lima, Value: 98 / Key: bravo, Value: 56 / Key: alpha, Value: 34 / +Key: kilo, Value: 43 / Key: delta, Value: 87 / Key: golf, Value: 34 / Key: foxtrot, Value: 12 / +sorted: +Key: alpha, Value: 34 / Key: bravo, Value: 56 / Key: charlie, Value: 23 / Key: delta, Value: 87 / +Key: echo, Value: 56 / Key: foxtrot, Value: 12 / Key: golf, Value: 34 / Key: hotel, Value: 16 / +Key: indio, Value: 87 / Key: juliet, Value: 65 / Key: kilo, Value: 43 / Key: lima, Value: 98 / +*/ diff --git a/eBook/examples/chapter_9/big.go b/eBook/examples/chapter_9/big.go index 22bc559..6da448c 100644 --- a/eBook/examples/chapter_9/big.go +++ b/eBook/examples/chapter_9/big.go @@ -1,30 +1,31 @@ -// big.go -package main - -import ( - "math" - "math/big" - "fmt" -) - -func main() { -// Here are some calculations with bigInts: - im := big.NewInt(math.MaxInt64) - in := im - io := big.NewInt(1956) - ip := big.NewInt(1) - ip.Mul(im, in).Add(ip, im).Div(ip, io) - fmt.Printf("Big Int: %v\n", ip) -// Here are some calculations with bigInts: - rm := big.NewRat(math.MaxInt64, 1956) - rn := big.NewRat(-1956, math.MaxInt64) - ro := big.NewRat(19, 56) - rp := big.NewRat(1111, 2222) - rq := big.NewRat(1, 1) - rq.Mul(rm, rn).Add(rq, ro).Mul(rq, rp) - fmt.Printf("Big Rat: %v\n", rq) -} -/* Output: -Big Int: 43492122561469640008497075573153004 -Big Rat: -37/112 -*/ +// big.go +package main + +import ( + "fmt" + "math" + "math/big" +) + +func main() { + // Here are some calculations with bigInts: + im := big.NewInt(math.MaxInt64) + in := im + io := big.NewInt(1956) + ip := big.NewInt(1) + ip.Mul(im, in).Add(ip, im).Div(ip, io) + fmt.Printf("Big Int: %v\n", ip) + // Here are some calculations with bigInts: + rm := big.NewRat(math.MaxInt64, 1956) + rn := big.NewRat(-1956, math.MaxInt64) + ro := big.NewRat(19, 56) + rp := big.NewRat(1111, 2222) + rq := big.NewRat(1, 1) + rq.Mul(rm, rn).Add(rq, ro).Mul(rq, rp) + fmt.Printf("Big Rat: %v\n", rq) +} + +/* Output: +Big Int: 43492122561469640008497075573153004 +Big Rat: -37/112 +*/ diff --git a/eBook/examples/chapter_9/book/book_main/main.go b/eBook/examples/chapter_9/book/book_main/main.go index 503bc2d..2e89a5a 100644 --- a/eBook/examples/chapter_9/book/book_main/main.go +++ b/eBook/examples/chapter_9/book/book_main/main.go @@ -1,14 +1,14 @@ -package main - -import ( - "fmt" - "book/pack1" -) - -func main() { - var test1 string - test1 = pack1.ReturnStr() - fmt.Printf("ReturnStr from package1: %s\n", test1) - fmt.Printf("Integer from package1: %d\n", pack1.Pack1Int) - //fmt.Printf("Float from package1: %f\n", pack1.pack1Float) -} +package main + +import ( + "book/pack1" + "fmt" +) + +func main() { + var test1 string + test1 = pack1.ReturnStr() + fmt.Printf("ReturnStr from package1: %s\n", test1) + fmt.Printf("Integer from package1: %d\n", pack1.Pack1Int) + //fmt.Printf("Float from package1: %f\n", pack1.pack1Float) +} diff --git a/eBook/examples/chapter_9/book/pack1/pack1.go b/eBook/examples/chapter_9/book/pack1/pack1.go index c4036ac..198952d 100644 --- a/eBook/examples/chapter_9/book/pack1/pack1.go +++ b/eBook/examples/chapter_9/book/pack1/pack1.go @@ -1,8 +1,8 @@ -package pack1 - -var Pack1Int int = 42 -var pack1Float = 3.14 - -func ReturnStr() string { - return "Hello main!" -} \ No newline at end of file +package pack1 + +var Pack1Int int = 42 +var pack1Float = 3.14 + +func ReturnStr() string { + return "Hello main!" +} diff --git a/eBook/examples/chapter_9/book/package_test.go b/eBook/examples/chapter_9/book/package_test.go index e98ecd3..5f2cb8a 100644 --- a/eBook/examples/chapter_9/book/package_test.go +++ b/eBook/examples/chapter_9/book/package_test.go @@ -1,14 +1,14 @@ package main import ( - "fmt" - "./pack1/pack1" + "./pack1/pack1" + "fmt" ) func main() { - var test1 string - test1 = pack1.ReturnStr() - fmt.Printf("ReturnStr from package1: %s\n", test1) - fmt.Printf("Integer from package1: %d\n", pack1.Pack1Int) - // fmt.Printf(“Float from package1: %f\n”, pack1.pack1Float) + var test1 string + test1 = pack1.ReturnStr() + fmt.Printf("ReturnStr from package1: %s\n", test1) + fmt.Printf("Integer from package1: %d\n", pack1.Pack1Int) + // fmt.Printf(“Float from package1: %f\n”, pack1.pack1Float) } diff --git a/eBook/examples/chapter_9/doc_example/sort.go b/eBook/examples/chapter_9/doc_example/sort.go index bced106..19e248d 100644 --- a/eBook/examples/chapter_9/doc_example/sort.go +++ b/eBook/examples/chapter_9/doc_example/sort.go @@ -1,59 +1,61 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Sorting using a general interface -package sort - -// Sorting interface -type Interface interface { - Len() int - Less(i, j int) bool - Swap(i, j int) -} - -// General sort function -func Sort(data Interface) { - for i := 1; i < data.Len(); i++ { - for j := i; j > 0 && data.Less(j, j-1); j-- { - data.Swap(j, j-1) - } - } -} - -// Test if data is sorted -func IsSorted(data Interface) bool { - n := data.Len() - for i := n - 1; i > 0; i-- { - if data.Less(i, i-1) { - return false - } - } - return true -} - -// Convenience types for common cases: IntArray -type IntArray []int - -func (p IntArray) Len() int { return len(p) } -func (p IntArray) Less(i, j int) bool { return p[i] < p[j] } -func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -type Float64Array []float64 -func (p Float64Array) Len() int { return len(p) } -func (p Float64Array) Less(i, j int) bool { return p[i] < p[j] } -func (p Float64Array) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -type StringArray []string -func (p StringArray) Len() int { return len(p) } -func (p StringArray) Less(i, j int) bool { return p[i] < p[j] } -func (p StringArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -// Convenience wrappers for common cases -func SortInts(a []int) { Sort(IntArray(a)) } -func SortFloat64s(a []float64) { Sort(Float64Array(a)) } -func SortStrings(a []string) { Sort(StringArray(a)) } - -func IntsAreSorted(a []int) bool { return IsSorted(IntArray(a)) } -func Float64sAreSorted(a []float64) bool { return IsSorted(Float64Array(a)) } -func StringsAreSorted(a []string) bool { return IsSorted(StringArray(a)) } \ No newline at end of file +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Sorting using a general interface +package sort + +// Sorting interface +type Interface interface { + Len() int + Less(i, j int) bool + Swap(i, j int) +} + +// General sort function +func Sort(data Interface) { + for i := 1; i < data.Len(); i++ { + for j := i; j > 0 && data.Less(j, j-1); j-- { + data.Swap(j, j-1) + } + } +} + +// Test if data is sorted +func IsSorted(data Interface) bool { + n := data.Len() + for i := n - 1; i > 0; i-- { + if data.Less(i, i-1) { + return false + } + } + return true +} + +// Convenience types for common cases: IntArray +type IntArray []int + +func (p IntArray) Len() int { return len(p) } +func (p IntArray) Less(i, j int) bool { return p[i] < p[j] } +func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +type Float64Array []float64 + +func (p Float64Array) Len() int { return len(p) } +func (p Float64Array) Less(i, j int) bool { return p[i] < p[j] } +func (p Float64Array) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +type StringArray []string + +func (p StringArray) Len() int { return len(p) } +func (p StringArray) Less(i, j int) bool { return p[i] < p[j] } +func (p StringArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +// Convenience wrappers for common cases +func SortInts(a []int) { Sort(IntArray(a)) } +func SortFloat64s(a []float64) { Sort(Float64Array(a)) } +func SortStrings(a []string) { Sort(StringArray(a)) } + +func IntsAreSorted(a []int) bool { return IsSorted(IntArray(a)) } +func Float64sAreSorted(a []float64) bool { return IsSorted(Float64Array(a)) } +func StringsAreSorted(a []string) bool { return IsSorted(StringArray(a)) } diff --git a/eBook/examples/chapter_9/doc_example/sortmain.go b/eBook/examples/chapter_9/doc_example/sortmain.go index da63508..20fd389 100644 --- a/eBook/examples/chapter_9/doc_example/sortmain.go +++ b/eBook/examples/chapter_9/doc_example/sortmain.go @@ -1,82 +1,81 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This package gives an example of how to use a custom package with interfaces -package main - -import ( - "fmt" - "./sort" -) - -// sorting of slice of integers -func ints() { - data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586} - a := sort.IntArray(data) //conversion to type IntArray - sort.Sort(a) - if !sort.IsSorted(a) { - panic("fail") - } - fmt.Printf("The sorted array is: %v\n", a) -} - -// sorting of slice of strings -func strings() { - data := []string{"monday", "friday", "tuesday", "wednesday", "sunday","thursday", "", "saturday"} - a := sort.StringArray(data) - sort.Sort(a) - if !sort.IsSorted(a) { - panic("fail") - } - fmt.Printf("The sorted array is: %v\n", a) -} - -// a type which describes a day of the week -type day struct { - num int - shortName string - longName string -} - -type dayArray struct { - data []*day -} - -func (p *dayArray) Len() int { return len(p.data) } -func (p *dayArray) Less(i, j int) bool { return p.data[i].num < p.data[j].num } -func (p *dayArray) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i] } - -// sorting of custom type day -func days() { - Sunday := day{0, "SUN", "Sunday"} - Monday := day{1, "MON", "Monday"} - Tuesday := day{2, "TUE", "Tuesday"} - Wednesday := day{3, "WED", "Wednesday"} - Thursday := day{4, "THU", "Thursday"} - Friday := day{5, "FRI", "Friday"} - Saturday := day{6, "SAT", "Saturday"} - data := []*day{&Tuesday, &Thursday, &Wednesday, &Sunday, &Monday, &Friday, &Saturday} - a := dayArray{data} - sort.Sort(&a) - if !sort.IsSorted(&a) { - panic("fail") - } - for _, d := range data { - fmt.Printf("%s ", d.longName) - } - fmt.Printf("\n") -} - - -func main() { - ints() - strings() - days() -} - -/* Output: -The sorted array is: [-5467984 -784 0 0 42 59 74 238 905 959 7586 7586 9845] -The sorted array is: [ friday monday saturday sunday thursday tuesday wednesday] -Sunday Monday Tuesday Wednesday Thursday Friday Saturday -*/ \ No newline at end of file +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This package gives an example of how to use a custom package with interfaces +package main + +import ( + "./sort" + "fmt" +) + +// sorting of slice of integers +func ints() { + data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586} + a := sort.IntArray(data) //conversion to type IntArray + sort.Sort(a) + if !sort.IsSorted(a) { + panic("fail") + } + fmt.Printf("The sorted array is: %v\n", a) +} + +// sorting of slice of strings +func strings() { + data := []string{"monday", "friday", "tuesday", "wednesday", "sunday", "thursday", "", "saturday"} + a := sort.StringArray(data) + sort.Sort(a) + if !sort.IsSorted(a) { + panic("fail") + } + fmt.Printf("The sorted array is: %v\n", a) +} + +// a type which describes a day of the week +type day struct { + num int + shortName string + longName string +} + +type dayArray struct { + data []*day +} + +func (p *dayArray) Len() int { return len(p.data) } +func (p *dayArray) Less(i, j int) bool { return p.data[i].num < p.data[j].num } +func (p *dayArray) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i] } + +// sorting of custom type day +func days() { + Sunday := day{0, "SUN", "Sunday"} + Monday := day{1, "MON", "Monday"} + Tuesday := day{2, "TUE", "Tuesday"} + Wednesday := day{3, "WED", "Wednesday"} + Thursday := day{4, "THU", "Thursday"} + Friday := day{5, "FRI", "Friday"} + Saturday := day{6, "SAT", "Saturday"} + data := []*day{&Tuesday, &Thursday, &Wednesday, &Sunday, &Monday, &Friday, &Saturday} + a := dayArray{data} + sort.Sort(&a) + if !sort.IsSorted(&a) { + panic("fail") + } + for _, d := range data { + fmt.Printf("%s ", d.longName) + } + fmt.Printf("\n") +} + +func main() { + ints() + strings() + days() +} + +/* Output: +The sorted array is: [-5467984 -784 0 0 42 59 74 238 905 959 7586 7586 9845] +The sorted array is: [ friday monday saturday sunday thursday tuesday wednesday] +Sunday Monday Tuesday Wednesday Thursday Friday Saturday +*/ diff --git a/eBook/examples/chapter_9/pattern.go b/eBook/examples/chapter_9/pattern.go index a232392..c343f76 100644 --- a/eBook/examples/chapter_9/pattern.go +++ b/eBook/examples/chapter_9/pattern.go @@ -1,35 +1,36 @@ -// pattern.go -package main - -import ( - "fmt" - "regexp" - "strconv" -) - -func main() { - searchIn := "John: 2578.34 William: 4567.23 Steve: 5632.18" // string to search - pat := "[0-9]+.[0-9]+" // pattern search for in searchIn - - f := func (s string) string { - v, _ := strconv.ParseFloat(s, 32) - return strconv.FormatFloat(v * 2, 'f', 2, 32) - } - - if ok, _ := regexp.Match(pat, []byte(searchIn)); ok { - fmt.Println("Match found!") - } - - re, _ := regexp.Compile(pat) - str := re.ReplaceAllString(searchIn, "##.#") // replace pat with "##.#" - fmt.Println(str) - // using a function : - str2 := re.ReplaceAllStringFunc(searchIn, f) - fmt.Println(str2) - -} -/* Output: -Match found! -John: ##.# William: ##.# Steve: ##.# -John: 5156.68 William: 9134.46 Steve: 11264.36 -*/ \ No newline at end of file +// pattern.go +package main + +import ( + "fmt" + "regexp" + "strconv" +) + +func main() { + searchIn := "John: 2578.34 William: 4567.23 Steve: 5632.18" // string to search + pat := "[0-9]+.[0-9]+" // pattern search for in searchIn + + f := func(s string) string { + v, _ := strconv.ParseFloat(s, 32) + return strconv.FormatFloat(v*2, 'f', 2, 32) + } + + if ok, _ := regexp.Match(pat, []byte(searchIn)); ok { + fmt.Println("Match found!") + } + + re, _ := regexp.Compile(pat) + str := re.ReplaceAllString(searchIn, "##.#") // replace pat with "##.#" + fmt.Println(str) + // using a function : + str2 := re.ReplaceAllStringFunc(searchIn, f) + fmt.Println(str2) + +} + +/* Output: +Match found! +John: ##.# William: ##.# Steve: ##.# +John: 5156.68 William: 9134.46 Steve: 11264.36 +*/ diff --git a/eBook/examples/chapter_9/reboot.go b/eBook/examples/chapter_9/reboot.go index 7250e06..9239b9e 100644 --- a/eBook/examples/chapter_9/reboot.go +++ b/eBook/examples/chapter_9/reboot.go @@ -1,21 +1,21 @@ -// reboot.go -// compile errors (Windows): -//undefined: syscall.SYS_REBOOT -// reboot.go:13: not enough arguments in call to syscall.Syscall -// Linux: compileert, uitvoeren met sudo ./6.out --> systeem herstart -package main - -import ( - "syscall" -) - -const LINUX_REBOOT_MAGIC1 uintptr = 0xfee1dead -const LINUX_REBOOT_MAGIC2 uintptr = 672274793 -const LINUX_REBOOT_CMD_RESTART uintptr = 0x1234567 - -func main() { - syscall.Syscall(syscall.SYS_REBOOT, - LINUX_REBOOT_MAGIC1, - LINUX_REBOOT_MAGIC2, - LINUX_REBOOT_CMD_RESTART) -} +// reboot.go +// compile errors (Windows): +//undefined: syscall.SYS_REBOOT +// reboot.go:13: not enough arguments in call to syscall.Syscall +// Linux: compileert, uitvoeren met sudo ./6.out --> systeem herstart +package main + +import ( + "syscall" +) + +const LINUX_REBOOT_MAGIC1 uintptr = 0xfee1dead +const LINUX_REBOOT_MAGIC2 uintptr = 672274793 +const LINUX_REBOOT_CMD_RESTART uintptr = 0x1234567 + +func main() { + syscall.Syscall(syscall.SYS_REBOOT, + LINUX_REBOOT_MAGIC1, + LINUX_REBOOT_MAGIC2, + LINUX_REBOOT_CMD_RESTART) +} diff --git a/eBook/examples/chapter_9/test.go b/eBook/examples/chapter_9/test.go index 340f036..387bb7c 100644 --- a/eBook/examples/chapter_9/test.go +++ b/eBook/examples/chapter_9/test.go @@ -7,9 +7,9 @@ type ucTest struct { } var ucTests = []ucTest{ - ucTest{"abc", "ABC"}, - ucTest{"cvo-az", "CVO-AZ"}, - ucTest{"Antwerp", "ANTWERP"}, + {"abc", "ABC"}, + {"cvo-az", "CVO-AZ"}, + {"Antwerp", "ANTWERP"}, } func TestUC(t *testing.T) { diff --git a/eBook/examples/chapter_9/uppercase/uc/uc.go b/eBook/examples/chapter_9/uppercase/uc/uc.go index 221c5ab..7271a34 100644 --- a/eBook/examples/chapter_9/uppercase/uc/uc.go +++ b/eBook/examples/chapter_9/uppercase/uc/uc.go @@ -1,8 +1,8 @@ -// uc.go -package uc - -import "strings" - -func UpperCase(str string) string { - return strings.ToUpper(str) -} +// uc.go +package uc + +import "strings" + +func UpperCase(str string) string { + return strings.ToUpper(str) +} diff --git a/eBook/examples/chapter_9/uppercase/uc/uc_test.go b/eBook/examples/chapter_9/uppercase/uc/uc_test.go index 3d01c71..8cb7351 100644 --- a/eBook/examples/chapter_9/uppercase/uc/uc_test.go +++ b/eBook/examples/chapter_9/uppercase/uc/uc_test.go @@ -1,23 +1,23 @@ -// uc_test.go -package uc - -import "testing" - -type ucTest struct { - in, out string -} - -var ucTests = []ucTest { - ucTest{"abc", "ABC"}, - ucTest{"cvo-az", "CVO-AZ"}, - ucTest{"Antwerp", "ANTWERP"}, -} - -func TestUC(t *testing.T) { - for _, ut := range ucTests { - uc := UpperCase(ut.in) - if uc != ut.out { - t.Errorf("UpperCase(%s) = %s, must be %s.", ut.in, uc, ut.out) - } - } -} +// uc_test.go +package uc + +import "testing" + +type ucTest struct { + in, out string +} + +var ucTests = []ucTest{ + {"abc", "ABC"}, + {"cvo-az", "CVO-AZ"}, + {"Antwerp", "ANTWERP"}, +} + +func TestUC(t *testing.T) { + for _, ut := range ucTests { + uc := UpperCase(ut.in) + if uc != ut.out { + t.Errorf("UpperCase(%s) = %s, must be %s.", ut.in, uc, ut.out) + } + } +} diff --git a/eBook/examples/chapter_9/uppercase/uc_main/ucmain.go b/eBook/examples/chapter_9/uppercase/uc_main/ucmain.go index a415f2f..59288fa 100644 --- a/eBook/examples/chapter_9/uppercase/uc_main/ucmain.go +++ b/eBook/examples/chapter_9/uppercase/uc_main/ucmain.go @@ -1,12 +1,12 @@ -// main.go -package main - -import ( - "fmt" - "uppercase/uc" -) - -func main() { - str1 := "USING package uc!" - fmt.Println(uc.UpperCase(str1)) -} +// main.go +package main + +import ( + "fmt" + "uppercase/uc" +) + +func main() { + str1 := "USING package uc!" + fmt.Println(uc.UpperCase(str1)) +} diff --git a/eBook/examples/chapter_9/use_urlshortener.go b/eBook/examples/chapter_9/use_urlshortener.go index eede5e1..7f9cbf0 100644 --- a/eBook/examples/chapter_9/use_urlshortener.go +++ b/eBook/examples/chapter_9/use_urlshortener.go @@ -1,55 +1,55 @@ -// use_urlshortener.go -package main - -import ( - "fmt" - "net/http" - "text/template" - urlshortener "code.google.com/p/google-api-go-client/urlshortener/v1" -) - -func main() { - http.HandleFunc("/", root) - http.HandleFunc("/short", short) - http.HandleFunc("/long", long) - http.ListenAndServe("localhost:8080", nil) -} - -// the template used to show the forms and the results web page to the user -var rootHtmlTmpl = template.Must(template.New("rootHtml").Parse(` - -

URL SHORTENER

-{{if .}}{{.}}

{{end}} -
-Shorten this: - -
-
-
-Expand this: http://goo.gl/ - -
- -`)) - -func root(w http.ResponseWriter, r *http.Request) { - rootHtmlTmpl.Execute(w, nil) -} - -func short(w http.ResponseWriter, r *http.Request) { - longUrl := r.FormValue("longUrl") - urlshortenerSvc, _ := urlshortener.New(http.DefaultClient) - url, _ := urlshortenerSvc.Url.Insert(&urlshortener.Url{LongUrl: longUrl,}).Do() - rootHtmlTmpl.Execute(w, fmt.Sprintf("Shortened version of %s is : %s", longUrl, url.Id)) -} - -func long(w http.ResponseWriter, r *http.Request) { - shortUrl := "http://goo.gl/" + r.FormValue("shortUrl") - urlshortenerSvc, _ := urlshortener.New(http.DefaultClient) - url, err := urlshortenerSvc.Url.Get(shortUrl).Do() - if err != nil { - fmt.Println("error: %v", err) - return - } - rootHtmlTmpl.Execute(w, fmt.Sprintf("Longer version of %s is : %s", shortUrl, url.LongUrl)) -} \ No newline at end of file +// use_urlshortener.go +package main + +import ( + urlshortener "code.google.com/p/google-api-go-client/urlshortener/v1" + "fmt" + "net/http" + "text/template" +) + +func main() { + http.HandleFunc("/", root) + http.HandleFunc("/short", short) + http.HandleFunc("/long", long) + http.ListenAndServe("localhost:8080", nil) +} + +// the template used to show the forms and the results web page to the user +var rootHtmlTmpl = template.Must(template.New("rootHtml").Parse(` + +

URL SHORTENER

+{{if .}}{{.}}

{{end}} +
+Shorten this: + +
+
+
+Expand this: http://goo.gl/ + +
+ +`)) + +func root(w http.ResponseWriter, r *http.Request) { + rootHtmlTmpl.Execute(w, nil) +} + +func short(w http.ResponseWriter, r *http.Request) { + longUrl := r.FormValue("longUrl") + urlshortenerSvc, _ := urlshortener.New(http.DefaultClient) + url, _ := urlshortenerSvc.Url.Insert(&urlshortener.Url{LongUrl: longUrl}).Do() + rootHtmlTmpl.Execute(w, fmt.Sprintf("Shortened version of %s is : %s", longUrl, url.Id)) +} + +func long(w http.ResponseWriter, r *http.Request) { + shortUrl := "http://goo.gl/" + r.FormValue("shortUrl") + urlshortenerSvc, _ := urlshortener.New(http.DefaultClient) + url, err := urlshortenerSvc.Url.Get(shortUrl).Do() + if err != nil { + fmt.Println("error: %v", err) + return + } + rootHtmlTmpl.Execute(w, fmt.Sprintf("Longer version of %s is : %s", shortUrl, url.LongUrl)) +}