fix: coding style and file format for all example.

This commit is contained in:
Bo-Yi Wu
2017-02-11 12:34:46 +08:00
parent f215102638
commit 416e29d95a
206 changed files with 5531 additions and 5451 deletions

View File

@@ -37,6 +37,7 @@ func (l *Log) String() string {
func (c *Customer) Log() *Log { func (c *Customer) Log() *Log {
return c.log return c.log
} }
/* Output: /* Output:
1 - Yes we can! 1 - Yes we can!
2 - After me the world will be a better place! 2 - After me the world will be a better place!

View File

@@ -1,8 +1,8 @@
package main package main
import ( import (
"fmt"
"./struct_pack/structPack" "./struct_pack/structPack"
"fmt"
) )
func main() { func main() {
@@ -12,5 +12,6 @@ func main() {
fmt.Printf("Mi1 = %d\n", struct1.Mi1) fmt.Printf("Mi1 = %d\n", struct1.Mi1)
fmt.Printf("Mf1 = %f\n", struct1.Mf1) fmt.Printf("Mf1 = %f\n", struct1.Mf1)
} }
// Mi1 = 10 // Mi1 = 10
// Mf1 = 16.000000 // Mf1 = 16.000000

View File

@@ -19,6 +19,7 @@ func main() {
fmt.Println("Full time now:", m.String()) //calling existing String method on anonymous Time field 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 fmt.Println("First 3 chars:", m.first3Chars()) //calling myTime.first3Chars
} }
/* Output: /* Output:
Full time now: Mon Oct 24 15:34:54 Romance Daylight Time 2011 Full time now: Mon Oct 24 15:34:54 Romance Daylight Time 2011
First 3 chars: Mon First 3 chars: Mon

View File

@@ -23,5 +23,3 @@ func main() {
func (tn *TwoInts) String() string { func (tn *TwoInts) String() string {
return "(" + strconv.Itoa(tn.a) + " / " + strconv.Itoa(tn.b) + ")" return "(" + strconv.Itoa(tn.a) + " / " + strconv.Itoa(tn.b) + ")"
} }

View File

@@ -6,6 +6,7 @@ import (
) )
type List []int type List []int
func (l List) Len() int { return len(l) } func (l List) Len() int { return len(l) }
func (l *List) Append(val int) { *l = append(*l, val) } func (l *List) Append(val int) { *l = append(*l, val) }

View File

@@ -3,15 +3,15 @@ package main
import "fmt" import "fmt"
type Camera struct { } type Camera struct{}
func (c *Camera) TakeAPicture() string { func (c *Camera) TakeAPicture() string {
return "Click" return "Click"
} }
type Phone struct { } type Phone struct{}
func (p *Phone ) Call() string { func (p *Phone) Call() string {
return "Ring Ring" return "Ring Ring"
} }
@@ -27,6 +27,7 @@ func main() {
fmt.Println("It exhibits behavior of a Camera: ", cp.TakeAPicture()) fmt.Println("It exhibits behavior of a Camera: ", cp.TakeAPicture())
fmt.Println("It works like a Phone too: ", cp.Call()) fmt.Println("It works like a Phone too: ", cp.Call())
} }
/* Output: /* Output:
Our new CameraPhone exhibits multiple behaviors ... Our new CameraPhone exhibits multiple behaviors ...
It exhibits behavior of a Camera: Click It exhibits behavior of a Camera: Click

View File

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

View File

@@ -12,6 +12,3 @@ func (p *Person) FirstName() string {
func (p *Person) SetFirstName(newName string) { func (p *Person) SetFirstName(newName string) {
p.firstName = newName p.firstName = newName
} }

View File

@@ -22,6 +22,7 @@ func main() {
b2.change() b2.change()
fmt.Println(b2.write()) fmt.Println(b2.write())
} }
/* Output: /* Output:
{1} {1}
{1} {1}

View File

@@ -21,4 +21,5 @@ func main() {
var c = number(b) var c = number(b)
fmt.Println(a, b, c) fmt.Println(a, b, c)
} }
// output: {5} {5} {5} // output: {5} {5} {5}

View File

@@ -13,7 +13,7 @@ type TagType struct { // tags
func main() { func main() {
tt := TagType{true, "Barak Obama", 1} tt := TagType{true, "Barak Obama", 1}
for i:= 0; i < 3; i++ { for i := 0; i < 3; i++ {
refTag(tt, i) refTag(tt, i)
} }
} }
@@ -23,6 +23,7 @@ func refTag(tt TagType, ix int) {
ixField := ttType.Field(ix) ixField := ttType.Field(ix)
fmt.Printf("%v\n", ixField.Tag) fmt.Printf("%v\n", ixField.Tag)
} }
/* Output: /* Output:
An important answer An important answer
The name of the thing The name of the thing

View File

@@ -1,8 +1,8 @@
package main package main
import ( import (
"fmt"
"./person" "./person"
"fmt"
) )
func main() { func main() {

View File

@@ -5,7 +5,6 @@ import (
"fmt" "fmt"
) )
type Any interface{} type Any interface{}
type Car struct { type Car struct {
Model string Model string
@@ -17,7 +16,7 @@ type Cars []*Car
func main() { func main() {
// make some cars: // make some cars:
ford := &Car{"Fiesta","Ford", 2008} ford := &Car{"Fiesta", "Ford", 2008}
bmw := &Car{"XL 450", "BMW", 2011} bmw := &Car{"XL 450", "BMW", 2011}
merc := &Car{"D600", "Mercedes", 2009} merc := &Car{"D600", "Mercedes", 2009}
bmw2 := &Car{"X 800", "BMW", 2008} bmw2 := &Car{"X 800", "BMW", 2008}

View File

@@ -29,4 +29,5 @@ func TypeSwitch() {
func main() { func main() {
TypeSwitch() TypeSwitch()
} }
// Output: any hello is a special String! // Output: any hello is a special String!

View File

@@ -27,4 +27,5 @@ func main() {
areaIntf := sq1 areaIntf := sq1
fmt.Printf("The square has area: %f\n", areaIntf.Area()) fmt.Printf("The square has area: %f\n", areaIntf.Area())
} }
// The square has area: 25.000000 // The square has area: 25.000000

View File

@@ -28,11 +28,12 @@ func main() {
q := &Square{5} // Area() of Square needs a pointer q := &Square{5} // Area() of Square needs a pointer
shapes := []Shaper{r, q} shapes := []Shaper{r, q}
fmt.Println("Looping through shapes for area ...") fmt.Println("Looping through shapes for area ...")
for n, _ := range shapes { for n := range shapes {
fmt.Println("Shape details: ", shapes[n]) fmt.Println("Shape details: ", shapes[n])
fmt.Println("Area of this shape is: ", shapes[n].Area()) fmt.Println("Area of this shape is: ", shapes[n].Area())
} }
} }
/* Output: /* Output:
Looping through shapes for area ... Looping through shapes for area ...
Shape details: {5 3} Shape details: {5 3}
@@ -40,6 +41,3 @@ Area of this shape is: 15
Shape details: &{5} Shape details: &{5}
Area of this shape is: 25 Area of this shape is: 25
*/ */

View File

@@ -6,6 +6,7 @@ import (
) )
type List []int type List []int
func (l List) Len() int { return len(l) } func (l List) Len() int { return len(l) }
func (l *List) Append(val int) { *l = append(*l, val) } func (l *List) Append(val int) { *l = append(*l, val) }

View File

@@ -40,17 +40,18 @@ func main() {
q := &Square{5} // Area() of Square needs a pointer q := &Square{5} // Area() of Square needs a pointer
shapes := []Shaper{r, q} shapes := []Shaper{r, q}
fmt.Println("Looping through shapes for area ...") fmt.Println("Looping through shapes for area ...")
for n, _ := range shapes { for n := range shapes {
fmt.Println("Shape details: ", shapes[n]) fmt.Println("Shape details: ", shapes[n])
fmt.Println("Area of this shape is: ", shapes[n].Area()) fmt.Println("Area of this shape is: ", shapes[n].Area())
} }
topgen := []TopologicalGenus{r, q} topgen := []TopologicalGenus{r, q}
fmt.Println("Looping through topgen for rank ...") fmt.Println("Looping through topgen for rank ...")
for n, _ := range topgen { for n := range topgen {
fmt.Println("Shape details: ", topgen[n]) fmt.Println("Shape details: ", topgen[n])
fmt.Println("Topological Genus of this shape is: ", topgen[n].Rank()) fmt.Println("Topological Genus of this shape is: ", topgen[n].Rank())
} }
} }
/* Output: /* Output:
Looping through shapes for area ... Looping through shapes for area ...
Shape details: {5 3} Shape details: {5 3}

View File

@@ -18,12 +18,12 @@ func (n *Node) SetData(data interface{}) {
} }
func main() { func main() {
root := NewNode(nil,nil) root := NewNode(nil, nil)
root.SetData("root node") root.SetData("root node")
// make child (leaf) nodes: // make child (leaf) nodes:
a := NewNode(nil,nil) a := NewNode(nil, nil)
a.SetData("left node") a.SetData("left node")
b := NewNode(nil,nil) b := NewNode(nil, nil)
b.SetData("right node") b.SetData("right node")
root.le = a root.le = a
root.ri = b root.ri = b

View File

@@ -13,7 +13,7 @@ type Stringer interface {
type Celsius float64 type Celsius float64
func (c Celsius) String() string { func (c Celsius) String() string {
return strconv.FormatFloat(float64(c),'f', 1, 64) + " °C" return strconv.FormatFloat(float64(c), 'f', 1, 64) + " °C"
} }
type Day int type Day int
@@ -26,13 +26,19 @@ func (day Day) String() string {
func print(args ...interface{}) { func print(args ...interface{}) {
for i, arg := range args { for i, arg := range args {
if i > 0 {os.Stdout.WriteString(" ")} if i > 0 {
os.Stdout.WriteString(" ")
}
switch a := arg.(type) { // type switch switch a := arg.(type) { // type switch
case Stringer: os.Stdout.WriteString(a.String()) case Stringer:
case int: os.Stdout.WriteString(strconv.Itoa(a)) os.Stdout.WriteString(a.String())
case string: os.Stdout.WriteString(a) case int:
os.Stdout.WriteString(strconv.Itoa(a))
case string:
os.Stdout.WriteString(a)
// more types // more types
default: os.Stdout.WriteString("???") default:
os.Stdout.WriteString("???")
} }
} }
} }
@@ -40,4 +46,5 @@ func print(args ...interface{}) {
func main() { func main() {
print(Day(1), "was", Celsius(18.36)) // Tuesday was 18.4 °C print(Day(1), "was", Celsius(18.36)) // Tuesday was 18.4 °C
} }
// Tuesday was 18.4 °C // Tuesday was 18.4 °C

View File

@@ -20,6 +20,7 @@ func main() {
y := v.Interface().(float64) y := v.Interface().(float64)
fmt.Println(y) fmt.Println(y)
} }
/* output: /* output:
type: float64 type: float64
value: <float64 Value> value: <float64 Value>

View File

@@ -22,6 +22,7 @@ func main() {
fmt.Println(v.Interface()) fmt.Println(v.Interface())
fmt.Println(v) fmt.Println(v)
} }
/* Output: /* Output:
settability of v: false settability of v: false
type of v: *float64 type of v: *float64

View File

@@ -15,7 +15,7 @@ func (n NotknownType) String() string {
} }
// variable to investigate: // variable to investigate:
var secret interface {} = NotknownType{"Ada", "Go", "Oberon"} var secret interface{} = NotknownType{"Ada", "Go", "Oberon"}
func main() { func main() {
value := reflect.ValueOf(secret) // <main.NotknownType Value> value := reflect.ValueOf(secret) // <main.NotknownType Value>
@@ -27,7 +27,7 @@ func main() {
fmt.Println(knd) fmt.Println(knd)
// iterate through the fields of the struct: // iterate through the fields of the struct:
for i:= 0; i < value.NumField(); i++ { for i := 0; i < value.NumField(); i++ {
fmt.Printf("Field %d: %v\n", i, value.Field(i)) fmt.Printf("Field %d: %v\n", i, value.Field(i))
// error: panic: reflect.Value.SetString using value obtained using unexported field // error: panic: reflect.Value.SetString using value obtained using unexported field
//value.Field(i).SetString("C#") //value.Field(i).SetString("C#")
@@ -37,6 +37,7 @@ func main() {
results := value.Method(0).Call(nil) results := value.Method(0).Call(nil)
fmt.Println(results) // [Ada - Go - Oberon] fmt.Println(results) // [Ada - Go - Oberon]
} }
/* Output: /* Output:
main.NotknownType main.NotknownType
struct struct

View File

@@ -24,6 +24,7 @@ func main() {
s.Field(1).SetString("Sunset Strip") s.Field(1).SetString("Sunset Strip")
fmt.Println("t is now", t) fmt.Println("t is now", t)
} }
/* Output: /* Output:
0: A int = 23 0: A int = 23
1: B string = skidoo 1: B string = skidoo

View File

@@ -39,11 +39,13 @@ 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] } func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
type Float64Array []float64 type Float64Array []float64
func (p Float64Array) Len() int { return len(p) } func (p Float64Array) Len() int { return len(p) }
func (p Float64Array) Less(i, j int) bool { return p[i] < p[j] } 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] } func (p Float64Array) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
type StringArray []string type StringArray []string
func (p StringArray) Len() int { return len(p) } func (p StringArray) Len() int { return len(p) }
func (p StringArray) Less(i, j int) bool { return p[i] < p[j] } 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] } func (p StringArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }

View File

@@ -6,8 +6,8 @@
package main package main
import ( import (
"fmt"
"./sort" "./sort"
"fmt"
) )
// sorting of slice of integers // sorting of slice of integers
@@ -23,7 +23,7 @@ func ints() {
// sorting of slice of strings // sorting of slice of strings
func strings() { func strings() {
data := []string{"monday", "friday", "tuesday", "wednesday", "sunday","thursday", "", "saturday"} data := []string{"monday", "friday", "tuesday", "wednesday", "sunday", "thursday", "", "saturday"}
a := sort.StringArray(data) a := sort.StringArray(data)
sort.Sort(a) sort.Sort(a)
if !sort.IsSorted(a) { if !sort.IsSorted(a) {
@@ -68,7 +68,6 @@ func days() {
fmt.Printf("\n") fmt.Printf("\n")
} }
func main() { func main() {
ints() ints()
strings() strings()

View File

@@ -2,11 +2,11 @@
package main package main
import ( import (
"io"
"os"
"bufio" "bufio"
"bytes" "bytes"
"fmt" "fmt"
"io"
"os"
) )
var r io.Reader var r io.Reader

View File

@@ -43,8 +43,8 @@ package cgl
import ( import (
"bytes" "bytes"
"crypto/rand" "crypto/rand"
"fmt"
"encoding/hex" "encoding/hex"
"fmt"
"io" "io"
"log" "log"
"reflect" "reflect"

View File

@@ -1,11 +1,11 @@
package main package main
import ( import (
"os"
"io"
"fmt"
"bufio" "bufio"
"flag" "flag"
"fmt"
"io"
"os"
) )
func cat(r *bufio.Reader) { func cat(r *bufio.Reader) {
@@ -33,4 +33,3 @@ func main() {
cat(bufio.NewReader(f)) cat(bufio.NewReader(f))
} }
} }

View File

@@ -1,8 +1,8 @@
package main package main
import ( import (
"os"
"flag" // command line option parser "flag" // command line option parser
"os"
) )
var NewLine = flag.Bool("n", false, "print newline") // echo -n flag, of type *bool var NewLine = flag.Bool("n", false, "print newline") // echo -n flag, of type *bool

View File

@@ -1,12 +1,12 @@
package main package main
import ( import (
"os"
"bufio" "bufio"
"fmt" "fmt"
"os"
) )
func main () { func main() {
// var outputWriter *bufio.Writer // var outputWriter *bufio.Writer
// var outputFile *os.File // var outputFile *os.File
// var outputError os.Error // var outputError os.Error
@@ -21,7 +21,7 @@ func main () {
outputWriter := bufio.NewWriter(outputFile) outputWriter := bufio.NewWriter(outputFile)
outputString := "hello world!\n" outputString := "hello world!\n"
for i:=0; i<10; i++ { for i := 0; i < 10; i++ {
outputWriter.WriteString(outputString) outputWriter.WriteString(outputString)
} }
outputWriter.Flush() outputWriter.Flush()

View File

@@ -3,8 +3,8 @@ package main
import ( import (
"bytes" "bytes"
"fmt"
"encoding/gob" "encoding/gob"
"fmt"
"log" "log"
) )
@@ -38,4 +38,5 @@ func main() {
} }
fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y) fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y)
} }
// Output: "Pythagoras": {3,4} // Output: "Pythagoras": {3,4}

View File

@@ -23,9 +23,9 @@ type VCard struct {
var content string var content string
func main() { func main() {
pa := &Address{"private", "Aartselaar","Belgium"} pa := &Address{"private", "Aartselaar", "Belgium"}
wa := &Address{"work", "Boom", "Belgium"} wa := &Address{"work", "Boom", "Belgium"}
vc := VCard{"Jan", "Kersschot", []*Address{pa,wa}, "none"} vc := VCard{"Jan", "Kersschot", []*Address{pa, wa}, "none"}
// fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none}: // fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none}:
// using an encoder: // using an encoder:
file, _ := os.OpenFile("vcard.gob", os.O_CREATE|os.O_WRONLY, 0666) file, _ := os.OpenFile("vcard.gob", os.O_CREATE|os.O_WRONLY, 0666)
@@ -36,4 +36,3 @@ func main() {
log.Println("Error in encoding gob") log.Println("Error in encoding gob")
} }
} }

View File

@@ -2,10 +2,10 @@
package main package main
import ( import (
"fmt"
"bufio" "bufio"
"os"
"compress/gzip" "compress/gzip"
"fmt"
"os"
) )
func main() { func main() {

View File

@@ -2,8 +2,8 @@
package main package main
import ( import (
"fmt"
"crypto/sha1" "crypto/sha1"
"fmt"
"io" "io"
"log" "log"
) )
@@ -18,12 +18,13 @@ func main() {
hasher.Reset() hasher.Reset()
data := []byte("We shall overcome!") data := []byte("We shall overcome!")
n, err := hasher.Write(data) n, err := hasher.Write(data)
if n!=len(data) || err!=nil { if n != len(data) || err != nil {
log.Printf("Hash write error: %v / %v", n, err) log.Printf("Hash write error: %v / %v", n, err)
} }
checksum := hasher.Sum(b) checksum := hasher.Sum(b)
fmt.Printf("Result: %x\n", checksum) fmt.Printf("Result: %x\n", checksum)
} }
/* Output: /* Output:
Result: a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 Result: a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
Result: [169 74 143 229 204 177 155 166 28 76 8 115 211 145 233 135 152 47 187 211] Result: [169 74 143 229 204 177 155 166 28 76 8 115 211 145 233 135 152 47 187 211]

View File

@@ -2,8 +2,8 @@
package main package main
import ( import (
"fmt"
"encoding/json" "encoding/json"
"fmt"
"log" "log"
"os" "os"
) )
@@ -22,9 +22,9 @@ type VCard struct {
} }
func main() { func main() {
pa := &Address{"private", "Aartselaar","Belgium"} pa := &Address{"private", "Aartselaar", "Belgium"}
wa := &Address{"work", "Boom", "Belgium"} wa := &Address{"work", "Boom", "Belgium"}
vc := VCard{"Jan", "Kersschot", []*Address{pa,wa}, "none"} vc := VCard{"Jan", "Kersschot", []*Address{pa, wa}, "none"}
// fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none}: // fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none}:
// JSON format: // JSON format:
js, _ := json.Marshal(vc) js, _ := json.Marshal(vc)

View File

@@ -32,6 +32,7 @@ func main() {
fmt.Printf("From XML: %#v\n", tx) fmt.Printf("From XML: %#v\n", tx)
} }
/* Output with /* Output with
type thing struct { type thing struct {
Field1 int Field1 int

View File

@@ -4,8 +4,8 @@ package main
import ( import (
"fmt" "fmt"
"os" "os"
// "io/ioutil" // "io/ioutil"
// "strings" // "strings"
) )
func main() { func main() {
@@ -31,6 +31,7 @@ func main() {
fmt.Println(col2) fmt.Println(col2)
fmt.Println(col3) fmt.Println(col3)
} }
/* Output: /* Output:
[ABC FUNC GO] [ABC FUNC GO]
[40 56 45] [40 56 45]

View File

@@ -21,9 +21,7 @@ func main() {
break break
} }
r := bufio.NewReader(fin) r := bufio.NewReader(fin)
for line, _, err := r.ReadLine(); for line, _, err := r.ReadLine(); err != io.EOF; line, _, err = r.ReadLine() {
err != io.EOF;
line, _, err = r.ReadLine() {
fmt.Printf("Lines: %v (error %v)\n", string(line), err) fmt.Printf("Lines: %v (error %v)\n", string(line), err)
} }
} }

View File

@@ -2,14 +2,14 @@
package main package main
import ( import (
"fmt"
"bufio" "bufio"
"fmt"
"os" "os"
) )
var inputReader *bufio.Reader var inputReader *bufio.Reader
var input string var input string
var err error var err error
func main() { func main() {
inputReader = bufio.NewReader(os.Stdin) // reader for input inputReader = bufio.NewReader(os.Stdin) // reader for input

View File

@@ -1,9 +1,9 @@
package main package main
import ( import (
"bufio"
"fmt" "fmt"
"os" "os"
"bufio"
) )
func main() { func main() {
@@ -19,23 +19,33 @@ func main() {
fmt.Printf("Your name is %s", input) fmt.Printf("Your name is %s", input)
// For Unix: test with delimiter "\n", for Windows: test with "\r\n" // For Unix: test with delimiter "\n", for Windows: test with "\r\n"
switch input { switch input {
case "Philip\r\n": fmt.Println("Welcome Philip!") case "Philip\r\n":
case "Chris\r\n": fmt.Println("Welcome Chris!") fmt.Println("Welcome Philip!")
case "Ivo\r\n": fmt.Println("Welcome Ivo!") case "Chris\r\n":
default: fmt.Printf("You are not welcome here! Goodbye!") fmt.Println("Welcome Chris!")
case "Ivo\r\n":
fmt.Println("Welcome Ivo!")
default:
fmt.Printf("You are not welcome here! Goodbye!")
} }
// version 2: // version 2:
switch input { switch input {
case "Philip\r\n": fallthrough case "Philip\r\n":
case "Ivo\r\n": fallthrough fallthrough
case "Chris\r\n": fmt.Printf("Welcome %s\n", input) case "Ivo\r\n":
default: fmt.Printf("You are not welcome here! Goodbye!\n") fallthrough
case "Chris\r\n":
fmt.Printf("Welcome %s\n", input)
default:
fmt.Printf("You are not welcome here! Goodbye!\n")
} }
// version 3: // version 3:
switch input { switch input {
case "Philip\r\n", "Ivo\r\n": fmt.Printf("Welcome %s\n", input) case "Philip\r\n", "Ivo\r\n":
default: fmt.Printf("You are not welcome here! Goodbye!\n") fmt.Printf("Welcome %s\n", input)
default:
fmt.Printf("You are not welcome here! Goodbye!\n")
} }
} }

View File

@@ -2,9 +2,9 @@
package main package main
import ( import (
"encoding/xml"
"fmt" "fmt"
"strings" "strings"
"encoding/xml"
) )
var t, token xml.Token var t, token xml.Token
@@ -30,13 +30,14 @@ func main() {
fmt.Println("End of token") fmt.Println("End of token")
case xml.CharData: case xml.CharData:
content := string([]byte(token)) content := string([]byte(token))
fmt.Printf("This is the content: %v\n", content ) fmt.Printf("This is the content: %v\n", content)
// ... // ...
default: default:
// ... // ...
} }
} }
} }
/* Output: /* Output:
Token name: Person Token name: Person
Token name: FirstName Token name: FirstName

View File

@@ -11,4 +11,5 @@ var errNotFound error = errors.New("Not found error")
func main() { func main() {
fmt.Printf("error: %v", errNotFound) fmt.Printf("error: %v", errNotFound)
} }
// error: Not found error // error: Not found error

View File

@@ -2,12 +2,12 @@
package main package main
import ( import (
"fmt"
"even/even" "even/even"
"fmt"
) )
func main() { func main() {
for i:=0; i<=100; i++ { for i := 0; i <= 100; i++ {
fmt.Printf("Is the integer %d even? %v\n", i, even.Even(i)) fmt.Printf("Is the integer %d even? %v\n", i, even.Even(i))
} }
} }

View File

@@ -1,15 +1,16 @@
// exec.go // exec.go
package main package main
import ( import (
"fmt" "fmt"
"os/exec"
"os" "os"
"os/exec"
) )
func main() { func main() {
// 1) os.StartProcess // // 1) os.StartProcess //
/*********************/ /*********************/
/* Linux: */ /* Linux: */
env := os.Environ() env := os.Environ()
procAttr := &os.ProcAttr{ procAttr := &os.ProcAttr{
Env: env, Env: env,
@@ -33,20 +34,20 @@ func main() {
os.Exit(1) os.Exit(1)
} }
fmt.Printf("The process id is %v", pid) fmt.Printf("The process id is %v", pid)
/* Output 1st: /* Output 1st:
The process id is &{2054 0}total 2056 The process id is &{2054 0}total 2056
-rwxr-xr-x 1 ivo ivo 1157555 2011-07-04 16:48 Mieken_exec -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 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 -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 -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 -rw-r--r-- 1 ivo ivo 180 2011-04-11 20:39 panic.go
*/ */
// 2) exec.Run // // 2) exec.Run //
/***************/ /***************/
// Linux: OK, but not for ls ? // Linux: OK, but not for ls ?
// cmd := exec.Command("ls", "-l") // no error, but doesn't show anything ? // 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("ls") // no error, but doesn't show anything ?
cmd := exec.Command("gedit") // this opens a gedit-window cmd := exec.Command("gedit") // this opens a gedit-window
err = cmd.Run() err = cmd.Run()
if err != nil { if err != nil {
@@ -54,8 +55,7 @@ The process id is &{2054 0}total 2056
os.Exit(1) os.Exit(1)
} }
fmt.Printf("The command is %v", cmd) fmt.Printf("The command is %v", cmd)
// The command is &{/bin/ls [ls -l] [] <nil> <nil> <nil> 0xf840000210 <nil> true [0xf84000ea50 0xf84000e9f0 0xf84000e9c0] [0xf84000ea50 0xf84000e9f0 0xf84000e9c0] [] [] 0xf8400128c0} // The command is &{/bin/ls [ls -l] [] <nil> <nil> <nil> 0xf840000210 <nil> 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! // in Windows: uitvoering: Error fork/exec /bin/ls: The system cannot find the path specified. starting process!

View File

@@ -2,8 +2,8 @@
package main package main
import ( import (
"fmt"
"./parse/parse" "./parse/parse"
"fmt"
) )
func main() { func main() {
@@ -25,6 +25,7 @@ func main() {
fmt.Println(nums) fmt.Println(nums)
} }
} }
/* Output: /* Output:
Parsing "1 2 3 4 5": Parsing "1 2 3 4 5":
[1 2 3 4 5] [1 2 3 4 5]

View File

@@ -3,8 +3,8 @@ package parse
import ( import (
"fmt" "fmt"
"strings"
"strconv" "strconv"
"strings"
) )
// A ParseError indicates an error in converting a word into an integer. // A ParseError indicates an error in converting a word into an integer.

View File

@@ -18,7 +18,7 @@ func BenchmarkChannelSync(b *testing.B) {
} }
close(ch) close(ch)
}() }()
for _ = range ch { for range ch {
} }
} }
@@ -30,6 +30,6 @@ func BenchmarkChannelBuffered(b *testing.B) {
} }
close(ch) close(ch)
}() }()
for _ = range ch { for range ch {
} }
} }

View File

@@ -7,7 +7,7 @@ import (
var ngoroutine = flag.Int("n", 100000, "how many goroutines") 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() { func main() {
flag.Parse() flag.Parse()

View File

@@ -13,4 +13,3 @@ func pump(ch chan int) {
ch <- i ch <- i
} }
} }

View File

@@ -47,6 +47,7 @@ func main() {
fmt.Println("Salary changed:") fmt.Println("Salary changed:")
fmt.Println(bs) fmt.Println(bs)
} }
/* Output: /* Output:
Person - name is: Smith Bill - salary is: 2500.50 Person - name is: Smith Bill - salary is: 2500.50
Salary changed: Salary changed:

View File

@@ -43,6 +43,7 @@ func BuildLazyIntEvaluator(evalFunc EvalFunc, initState Any) func() int {
return ef().(int) return ef().(int)
} }
} }
/* Output: /* Output:
0th even: 0 0th even: 0
1th even: 2 1th even: 2

View File

@@ -30,4 +30,5 @@ func getData(ch chan string) {
fmt.Printf("%s ", input) fmt.Printf("%s ", input)
} }
} }
// Washington Tripoli London Beijing Tokio // Washington Tripoli London Beijing Tokio

View File

@@ -26,4 +26,5 @@ func getData(ch chan string) {
fmt.Printf("%s ", input) fmt.Printf("%s ", input)
} }
} }
// Washington Tripoli London Beijing Tokio // Washington Tripoli London Beijing Tokio

View File

@@ -2,8 +2,8 @@ package main
import ( import (
"fmt" "fmt"
"time"
"runtime" "runtime"
"time"
) )
func main() { func main() {
@@ -24,26 +24,24 @@ func main() {
} }
func pump1(ch chan int) { func pump1(ch chan int) {
for i:=0; ; i++ { for i := 0; ; i++ {
ch <- i*2 ch <- i * 2
} }
} }
func pump2(ch chan int) { func pump2(ch chan int) {
for i:=0; ; i++ { for i := 0; ; i++ {
ch <- i+5 ch <- i + 5
} }
} }
func suck(ch1,ch2 chan int) { func suck(ch1, ch2 chan int) {
for i := 0; ; i++ { for i := 0; ; i++ {
select { select {
case v := <- ch1: case v := <-ch1:
fmt.Printf("%d - Received on channel 1: %d\n", i, v) fmt.Printf("%d - Received on channel 1: %d\n", i, v)
case v := <- ch2: case v := <-ch2:
fmt.Printf("%d - Received on channel 2: %d\n", i, v) fmt.Printf("%d - Received on channel 2: %d\n", i, v)
} }
} }
} }

View File

@@ -8,14 +8,14 @@ import (
var resume chan int var resume chan int
func integers() chan int { func integers() chan int {
yield := make (chan int) yield := make(chan int)
count := 0 count := 0
go func () { go func() {
for { for {
yield <- count yield <- count
count++ count++
} }
} () }()
return yield return yield
} }

View File

@@ -1,6 +1,7 @@
package main package main
const MAXREQS = 50 const MAXREQS = 50
var sem = make(chan int, MAXREQS) var sem = make(chan int, MAXREQS)
type Request struct { type Request struct {

View File

@@ -22,6 +22,7 @@ func main() {
} }
} }
} }
/* Output: /* Output:
. .
. .

View File

@@ -39,6 +39,7 @@ func main() {
} }
time.Sleep(1e9) time.Sleep(1e9)
} }
/* Output: /* Output:
0 1 2 3 4 0 1 2 3 4
4 4 4 4 4 4 4 4 4 4

View File

@@ -9,10 +9,9 @@ type nexter interface {
next() byte next() byte
} }
func nextFew1(n nexter, num int) []byte { func nextFew1(n nexter, num int) []byte {
var b []byte var b []byte
for i:=0; i < num; i++ { for i := 0; i < num; i++ {
b[i] = n.next() b[i] = n.next()
} }
return b return b
@@ -20,7 +19,7 @@ func nextFew1(n nexter, num int) []byte {
func nextFew2(n *nexter, num int) []byte { func nextFew2(n *nexter, num int) []byte {
var b []byte var b []byte
for i:=0; i < num; i++ { for i := 0; i < num; i++ {
b[i] = n.next() // compile error: n.next undefined (type *nexter has no field or method next) b[i] = n.next() // compile error: n.next undefined (type *nexter has no field or method next)
} }
return b return b

View File

@@ -11,6 +11,7 @@ URL: <input type="text" name="url">
<input type="submit" value="Add"> <input type="submit" value="Add">
</form> </form>
` `
var store = NewURLStore() var store = NewURLStore()
func main() { func main() {
@@ -29,7 +30,6 @@ func Redirect(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, url, http.StatusFound) http.Redirect(w, r, url, http.StatusFound)
} }
func Add(w http.ResponseWriter, r *http.Request) { func Add(w http.ResponseWriter, r *http.Request) {
url := r.FormValue("url") url := r.FormValue("url")
if url == "" { if url == "" {

View File

@@ -23,7 +23,6 @@ func Redirect(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, url, http.StatusFound) http.Redirect(w, r, url, http.StatusFound)
} }
func Add(w http.ResponseWriter, r *http.Request) { func Add(w http.ResponseWriter, r *http.Request) {
url := r.FormValue("url") url := r.FormValue("url")
if url == "" { if url == "" {

View File

@@ -1,7 +1,7 @@
package main package main
import ( import (
// "bufio" // "bufio"
"encoding/gob" "encoding/gob"
"io" "io"
"log" "log"

View File

@@ -5,8 +5,8 @@ import (
"errors" "errors"
"io" "io"
"log" "log"
"os"
"net/rpc" "net/rpc"
"os"
"sync" "sync"
) )

View File

@@ -4,4 +4,3 @@ package main
func main() { func main() {
println("Hello", "world") println("Hello", "world")
} }

View File

@@ -8,5 +8,6 @@ import (
func main() { func main() {
fmt.Printf("%s", runtime.Version()) fmt.Printf("%s", runtime.Version())
} }
// Output: // Output:
// go1.0.3 or go 1.1 // go1.0.3 or go 1.1

View File

@@ -24,6 +24,7 @@ const signTemplateHTML = `
</body> </body>
</html> </html>
` `
var signTemplate = template.Must(template.New("sign").Parse(signTemplateHTML)) var signTemplate = template.Must(template.New("sign").Parse(signTemplateHTML))
func init() { func init() {
@@ -43,4 +44,3 @@ func sign(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.String(), http.StatusInternalServerError) http.Error(w, err.String(), http.StatusInternalServerError)
} }
} }

View File

@@ -28,6 +28,7 @@ const guestbookTemplateHTML = `
</body> </body>
</html> </html>
` `
var guestbookTemplate = template.Must(template.New("book").Parse(guestbookTemplateHTML)) var guestbookTemplate = template.Must(template.New("book").Parse(guestbookTemplateHTML))
type Greeting struct { type Greeting struct {

View File

@@ -13,4 +13,3 @@ func init() {
func handle(w http.ResponseWriter, r *http.Request) { func handle(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "<html><body>Hello, World! 세상아 안녕!! </body></html>") fmt.Fprint(w, "<html><body>Hello, World! 세상아 안녕!! </body></html>")
} }

View File

@@ -1,17 +1,19 @@
package main package main
import "fmt" import "fmt"
func main() { func main() {
var n int16 = 34 var n int16 = 34
var m int32 var m int32
// compiler error: cannot use n (type int16) as type int32 in assignment // compiler error: cannot use n (type int16) as type int32 in assignment
//m = n //m = n
m = int32(n) m = int32(n)
fmt.Printf("32 bit int is: %d\n", m) fmt.Printf("32 bit int is: %d\n", m)
fmt.Printf("16 bit int is: %d\n", n) fmt.Printf("16 bit int is: %d\n", n)
} }
/* Output: /* Output:
32 bit int is: 34 32 bit int is: 34
16 bit int is: 34 16 bit int is: 34

View File

@@ -14,6 +14,7 @@ func main() {
fmt.Printf("%X - %X - %X\n", ch, ch2, ch3) fmt.Printf("%X - %X - %X\n", ch, ch2, ch3)
fmt.Printf("%U - %U - %U", ch, ch2, ch3) fmt.Printf("%U - %U - %U", ch, ch2, ch3)
} }
/* Ouput: /* Ouput:
65 - 946 - 1053236 65 - 946 - 1053236
A - β - 􁈴 A - β - 􁈴

View File

@@ -1,5 +1,7 @@
package main package main
var a string var a string
func main() { func main() {
a = "G" a = "G"
print(a) print(a)

View File

@@ -1,5 +1,7 @@
package main package main
var a = "G" var a = "G"
func main() { func main() {
n() n()
m() m()

View File

@@ -1,5 +1,7 @@
package main package main
var a = "G" var a = "G"
func main() { func main() {
n() n()
m() m()

View File

@@ -11,4 +11,5 @@ func main() {
fmt.Printf("T/F? Does the string \"%s\" have prefix %s? ", str, "Th") fmt.Printf("T/F? Does the string \"%s\" have prefix %s? ", str, "Th")
fmt.Printf("%t\n", strings.HasPrefix(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 // Output: T/F? Does the string "This is an example of a string" have prefix Th? true

View File

@@ -22,6 +22,7 @@ func main() {
fmt.Printf("%2.2f / ", 100*rand.Float32()) fmt.Printf("%2.2f / ", 100*rand.Float32())
} }
} }
/* Output: /* Output:
134020434 / 1597969999 / 1721070109 / 2068675587 / 1237770961 / 220031192 / 2031484958 / 583324308 / 958990240 / 413002649 / 6 / 7 / 2 / 1 / 0 / 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 / 22.84 / 10.12 / 44.32 / 58.58 / 15.49 / 12.23 / 30.16 / 88.48 / 34.26 / 27.18 /

View File

@@ -21,9 +21,10 @@ func main() {
fmt.Printf("%s - ", val) fmt.Printf("%s - ", val)
} }
fmt.Println() fmt.Println()
str3 := strings.Join(sl2,";") str3 := strings.Join(sl2, ";")
fmt.Printf("sl2 joined by ;: %s\n", str3) fmt.Printf("sl2 joined by ;: %s\n", str3)
} }
/* Output: /* Output:
Splitted in slice: [The quick brown fox jumps over the lazy dog] Splitted in slice: [The quick brown fox jumps over the lazy dog]
The - quick - brown - fox - jumps - over - the - lazy - dog - The - quick - brown - fox - jumps - over - the - lazy - dog -

View File

@@ -7,5 +7,6 @@ func main() {
*p = 0 *p = 0
} }
// in Windows: stops only with: <exit code="-1073741819" msg="process crashed"/> // in Windows: stops only with: <exit code="-1073741819" msg="process crashed"/>
// runtime error: invalid memory address or nil pointer dereference // runtime error: invalid memory address or nil pointer dereference

View File

@@ -1,8 +1,8 @@
package main package main
import ( import (
"fmt"
"./trans" "./trans"
"fmt"
) )
var twoPi = 2 * trans.Pi // decl computes twoPi var twoPi = 2 * trans.Pi // decl computes twoPi

View File

@@ -1,9 +1,12 @@
package main package main
import ( import (
"fmt"
"./trans" "./trans"
"fmt"
) )
var twoPi = 2 * trans.Pi var twoPi = 2 * trans.Pi
func main() { func main() {
fmt.Printf("2*Pi = %g\n", twoPi) // 2*Pi = 6.283185307179586 fmt.Printf("2*Pi = %g\n", twoPi) // 2*Pi = 6.283185307179586
} }

View File

@@ -1,9 +1,9 @@
package main package main
func main() { func main() {
for i:=0; i<3; i++ { for i := 0; i < 3; i++ {
for j:=0; j<10; j++ { for j := 0; j < 10; j++ {
if j>5 { if j > 5 {
break break
} }
print(j) print(j)

View File

@@ -6,15 +6,16 @@ import "fmt"
func main() { func main() {
str := "Go is a beautiful language!" str := "Go is a beautiful language!"
fmt.Printf("The length of str is: %d\n", len(str)) fmt.Printf("The length of str is: %d\n", len(str))
for ix :=0; ix < len(str); ix++ { for ix := 0; ix < len(str); ix++ {
fmt.Printf("Character on position %d is: %c \n", ix, str[ix]) fmt.Printf("Character on position %d is: %c \n", ix, str[ix])
} }
str2 := "日本語" str2 := "日本語"
fmt.Printf("The length of str2 is: %d\n", len(str2)) fmt.Printf("The length of str2 is: %d\n", len(str2))
for ix :=0; ix < len(str2); ix++ { for ix := 0; ix < len(str2); ix++ {
fmt.Printf("Character on position %d is: %c \n", ix, str2[ix]) fmt.Printf("Character on position %d is: %c \n", ix, str2[ix])
} }
} }
/* Output: /* Output:
The length of str is: 27 The length of str is: 27
Character on position 0 is: G Character on position 0 is: G

View File

@@ -1,11 +1,11 @@
package main package main
func main() { func main() {
i:=0 i := 0
HERE: HERE:
print(i) print(i)
i++ i++
if i==5 { if i == 5 {
return return
} }
goto HERE goto HERE

View File

@@ -7,7 +7,7 @@ func main() {
a := 1 a := 1
goto TARGET // compile error goto TARGET // compile error
b := 9 b := 9
TARGET: TARGET:
b += a b += a
fmt.Printf("a is %v *** b is %v", a, b) fmt.Printf("a is %v *** b is %v", a, b)
} }

View File

@@ -20,6 +20,7 @@ func main() {
fmt.Printf("%-2d %d %U '%c' % X\n", index, rune, rune, rune, []byte(string(rune))) fmt.Printf("%-2d %d %U '%c' % X\n", index, rune, rune, rune, []byte(string(rune)))
} }
} }
/* Output: /* Output:
The length of str is: 27 The length of str is: 27
Character on position 0 is: G Character on position 0 is: G

View File

@@ -7,12 +7,12 @@ func main() {
doDBOperations() doDBOperations()
} }
func connectToDB () { func connectToDB() {
fmt.Println( "ok, connected to db" ) fmt.Println("ok, connected to db")
} }
func disconnectFromDB () { func disconnectFromDB() {
fmt.Println( "ok, disconnected from db" ) fmt.Println("ok, disconnected from db")
} }
func doDBOperations() { func doDBOperations() {
@@ -25,6 +25,7 @@ func doDBOperations() {
return //terminate the program return //terminate the program
// deferred function executed here just before actually returning, even if there is a return or abnormal termination before // deferred function executed here just before actually returning, even if there is a return or abnormal termination before
} }
/* Output: /* Output:
ok, connected to db ok, connected to db
Defering the database disconnect. Defering the database disconnect.
@@ -33,6 +34,3 @@ Oops! some crash or network error ...
Returning from function here! Returning from function here!
ok, disconnected from db ok, disconnected from db
*/ */

View File

@@ -16,4 +16,5 @@ func func1(s string) (n int, err error) {
func main() { func main() {
func1("Go") func1("Go")
} }
// Output: 2011/10/04 10:46:11 func1("Go") = 7, EOF // Output: 2011/10/04 10:46:11 func1("Go") = 7, EOF

View File

@@ -8,7 +8,7 @@ import (
func main() { func main() {
result := 0 result := 0
start := time.Now() start := time.Now()
for i:=0; i <= 25; i++ { for i := 0; i <= 25; i++ {
result = fibonacci(i) result = fibonacci(i)
fmt.Printf("fibonacci(%d) is: %d\n", i, result) fmt.Printf("fibonacci(%d) is: %d\n", i, result)
} }
@@ -25,6 +25,7 @@ func fibonacci(n int) (res int) {
} }
return return
} }
/* Output: /* Output:
fibonacci(0) is: 1 fibonacci(0) is: 1
fibonacci(1) is: 1 fibonacci(1) is: 1

View File

@@ -7,12 +7,13 @@ import (
) )
const LIM = 41 const LIM = 41
var fibs [LIM]uint64 var fibs [LIM]uint64
func main() { func main() {
var result uint64 = 0 var result uint64 = 0
start := time.Now() start := time.Now()
for i:=0; i < LIM; i++ { for i := 0; i < LIM; i++ {
result = fibonacci(i) result = fibonacci(i)
fmt.Printf("fibonacci(%d) is: %d\n", i, result) fmt.Printf("fibonacci(%d) is: %d\n", i, result)
} }
@@ -35,6 +36,7 @@ func fibonacci(n int) (res uint64) {
fibs[n] = res fibs[n] = res
return return
} }
/* /*
Output: LIM=40: Output: LIM=40:
normal (fibonacci.go): the calculation took this amount of time: 4.730270 s normal (fibonacci.go): the calculation took this amount of time: 4.730270 s

View File

@@ -1,18 +1,19 @@
// filter_factory.go // filter_factory.go
package main package main
import "fmt" import "fmt"
type flt func (int) bool type flt func(int) bool
type slice_split func([]int) ([]int, []int) type slice_split func([]int) ([]int, []int)
func isOdd(integer int) bool{ func isOdd(integer int) bool {
if integer%2 == 0 { if integer%2 == 0 {
return false return false
} }
return true return true
} }
func isBiggerThan4(integer int) bool{ func isBiggerThan4(integer int) bool {
if integer > 4 { if integer > 4 {
return true return true
} }
@@ -20,9 +21,9 @@ func isBiggerThan4(integer int) bool{
} }
func filter_factory(f flt) slice_split { func filter_factory(f flt) slice_split {
return func(s []int) (yes, no []int){ return func(s []int) (yes, no []int) {
for _, val := range s{ for _, val := range s {
if f(val){ if f(val) {
yes = append(yes, val) yes = append(yes, val)
} else { } else {
no = append(no, val) no = append(no, val)
@@ -32,8 +33,8 @@ func filter_factory(f flt) slice_split {
} }
} }
func main(){ func main() {
s := []int {1, 2, 3, 4, 5, 7} s := []int{1, 2, 3, 4, 5, 7}
fmt.Println("s = ", s) fmt.Println("s = ", s)
odd_even_function := filter_factory(isOdd) odd_even_function := filter_factory(isOdd)
odd, even := odd_even_function(s) odd, even := odd_even_function(s)
@@ -44,6 +45,7 @@ func main(){
fmt.Println("Bigger than 4: ", bigger) fmt.Println("Bigger than 4: ", bigger)
fmt.Println("Smaller than or equal to 4: ", smaller) fmt.Println("Smaller than or equal to 4: ", smaller)
} }
/* /*
s = [1 2 3 4 5 7] s = [1 2 3 4 5 7]
odd = [1 3 5 7] odd = [1 3 5 7]

View File

@@ -4,8 +4,8 @@ import "fmt"
func main() { func main() {
var f = Adder() var f = Adder()
fmt.Print(f(1)," - ") fmt.Print(f(1), " - ")
fmt.Print(f(20)," - ") fmt.Print(f(20), " - ")
fmt.Print(f(300)) fmt.Print(f(300))
} }

View File

@@ -1,5 +1,6 @@
// function_filter.go // function_filter.go
package main package main
import "fmt" import "fmt"
type flt func(int) bool type flt func(int) bool
@@ -33,14 +34,15 @@ func filter(sl []int, f flt) []int {
return res return res
} }
func main(){ func main() {
slice := []int {1, 2, 3, 4, 5, 7} slice := []int{1, 2, 3, 4, 5, 7}
fmt.Println("slice = ", slice) fmt.Println("slice = ", slice)
odd := filter(slice, isOdd) odd := filter(slice, isOdd)
fmt.Println("Odd elements of slice are: ", odd) fmt.Println("Odd elements of slice are: ", odd)
even := filter(slice, isEven) even := filter(slice, isEven)
fmt.Println("Even elements of slice are: ", even) fmt.Println("Even elements of slice are: ", even)
} }
/* /*
slice = [1 2 3 4 5 7] slice = [1 2 3 4 5 7]
Odd elements of slice are: [1 3 5 7] Odd elements of slice are: [1 3 5 7]

View File

@@ -1,4 +1,5 @@
package main package main
import "fmt" import "fmt"
func main() { func main() {

View File

@@ -9,12 +9,12 @@ func main() {
callback(1, Add) callback(1, Add)
} }
func Add(a,b int) { func Add(a, b int) {
fmt.Printf("The sum of %d and %d is: %d\n", a, b, a + b) fmt.Printf("The sum of %d and %d is: %d\n", a, b, a+b)
} }
func callback(y int, f func(int, int)) { func callback(y int, f func(int, int)) {
f(y, 2) // this becomes Add(1, 2) f(y, 2) // this becomes Add(1, 2)
} }
// Output: The sum of 1 and 2 is: 3 // Output: The sum of 1 and 2 is: 3

View File

@@ -1,4 +1,5 @@
package main package main
import "fmt" import "fmt"
func main() { func main() {
@@ -10,17 +11,18 @@ func main() {
fmt.Printf("The result is: %v\n", TwoAdder(2)) fmt.Printf("The result is: %v\n", TwoAdder(2))
} }
func Add2() (func(b int) int) { func Add2() func(b int) int {
return func(b int) int { return func(b int) int {
return b + 2 return b + 2
} }
} }
func Adder(a int) (func(b int) int) { func Adder(a int) func(b int) int {
return func(b int) int { return func(b int) int {
return a + b return a + b
} }
} }
/* Output: /* Output:
Call Add2 for 2 gives: 4 Call Add2 for 2 gives: 4
The result is: 4 The result is: 4

View File

@@ -12,16 +12,22 @@ func main() {
} }
func even(nr int) bool { func even(nr int) bool {
if nr == 0 {return true} if nr == 0 {
return odd(RevSign(nr)-1) return true
}
return odd(RevSign(nr) - 1)
} }
func odd(nr int) bool { func odd(nr int) bool {
if nr == 0 {return false} if nr == 0 {
return even(RevSign(nr)-1) return false
}
return even(RevSign(nr) - 1)
} }
func RevSign(nr int) int { func RevSign(nr int) int {
if nr < 0 {return -nr} if nr < 0 {
return -nr
}
return nr return nr
} }

View File

@@ -15,4 +15,5 @@ func f() (ret int) {
func main() { func main() {
fmt.Println(f()) fmt.Println(f())
} }
// Output: 2 // Output: 2

View File

@@ -5,13 +5,13 @@ import "fmt"
func main() { func main() {
x := Min(1, 3, 2, 0) x := Min(1, 3, 2, 0)
fmt.Printf("The minimum is: %d\n", x) fmt.Printf("The minimum is: %d\n", x)
arr := []int{7,9,3,5,1} arr := []int{7, 9, 3, 5, 1}
x = Min(arr...) x = Min(arr...)
fmt.Printf("The minimum in the array arr is: %d", x) fmt.Printf("The minimum in the array arr is: %d", x)
} }
func Min(a ...int) int { func Min(a ...int) int {
if len(a)==0 { if len(a) == 0 {
return 0 return 0
} }
min := a[0] min := a[0]
@@ -22,6 +22,7 @@ func Min(a ...int) int {
} }
return min return min
} }
/* /*
The minimum is: 0 The minimum is: 0
The minimum in the array arr is: 1 The minimum in the array arr is: 1

View File

@@ -14,4 +14,5 @@ func Sum(a *[3]float64) (sum float64) {
} }
return return
} }
// Output: The sum of the array is: 24.600000 // Output: The sum of the array is: 24.600000

View File

@@ -3,14 +3,14 @@ package main
import "fmt" import "fmt"
func main() { func main() {
sl_from := []int{1,2,3} sl_from := []int{1, 2, 3}
sl_to := make([]int,10) sl_to := make([]int, 10)
n := copy(sl_to, sl_from) n := copy(sl_to, sl_from)
fmt.Println(sl_to) // output: [1 2 3 0 0 0 0 0 0 0] fmt.Println(sl_to) // output: [1 2 3 0 0 0 0 0 0 0]
fmt.Printf("Copied %d elements\n", n) // n == 3 fmt.Printf("Copied %d elements\n", n) // n == 3
sl3 := []int{1,2,3} sl3 := []int{1, 2, 3}
sl3 = append(sl3, 4, 5, 6) sl3 = append(sl3, 4, 5, 6)
fmt.Println(sl3) // output: [1 2 3 4 5 6] fmt.Println(sl3) // output: [1 2 3 4 5 6]
} }

Some files were not shown because too many files have changed in this diff Show More