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 {
return c.log
}
/* Output:
1 - Yes we can!
2 - After me the world will be a better place!

View File

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

View File

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

View File

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

View File

@@ -3,15 +3,15 @@ package main
import "fmt"
type Camera struct { }
type Camera struct{}
func (c *Camera) TakeAPicture() string {
return "Click"
}
type Phone struct { }
type Phone struct{}
func (p *Phone ) Call() string {
func (p *Phone) Call() string {
return "Ring Ring"
}
@@ -27,6 +27,7 @@ func main() {
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

View File

@@ -10,30 +10,31 @@ type Person struct {
lastName string
}
func upPerson (p *Person) {
func upPerson(p *Person) {
p.firstName = strings.ToUpper(p.firstName)
p.lastName = strings.ToUpper(p.lastName)
}
func main() {
// 1- struct as a value type:
// 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:
// 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"}
// 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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -6,6 +6,7 @@ import (
)
type List []int
func (l List) Len() int { return len(l) }
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
shapes := []Shaper{r, q}
fmt.Println("Looping through shapes for area ...")
for n, _ := range shapes {
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 {
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}

View File

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

View File

@@ -13,7 +13,7 @@ type Stringer interface {
type Celsius float64
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
@@ -26,13 +26,19 @@ func (day Day) String() string {
func print(args ...interface{}) {
for i, arg := range args {
if i > 0 {os.Stdout.WriteString(" ")}
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)
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("???")
default:
os.Stdout.WriteString("???")
}
}
}
@@ -40,4 +46,5 @@ func print(args ...interface{}) {
func main() {
print(Day(1), "was", Celsius(18.36)) // Tuesday was 18.4 °C
}
// Tuesday was 18.4 °C

View File

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

View File

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

View File

@@ -15,7 +15,7 @@ func (n NotknownType) String() string {
}
// variable to investigate:
var secret interface {} = NotknownType{"Ada", "Go", "Oberon"}
var secret interface{} = NotknownType{"Ada", "Go", "Oberon"}
func main() {
value := reflect.ValueOf(secret) // <main.NotknownType Value>
@@ -27,7 +27,7 @@ func main() {
fmt.Println(knd)
// 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))
// error: panic: reflect.Value.SetString using value obtained using unexported field
//value.Field(i).SetString("C#")
@@ -37,6 +37,7 @@ func main() {
results := value.Method(0).Call(nil)
fmt.Println(results) // [Ada - Go - Oberon]
}
/* Output:
main.NotknownType
struct

View File

@@ -24,6 +24,7 @@ func main() {
s.Field(1).SetString("Sunset Strip")
fmt.Println("t is now", t)
}
/* Output:
0: A int = 23
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] }
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] }

View File

@@ -6,8 +6,8 @@
package main
import (
"fmt"
"./sort"
"fmt"
)
// sorting of slice of integers
@@ -23,7 +23,7 @@ func ints() {
// sorting of slice of 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)
sort.Sort(a)
if !sort.IsSorted(a) {
@@ -68,7 +68,6 @@ func days() {
fmt.Printf("\n")
}
func main() {
ints()
strings()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -23,9 +23,9 @@ type VCard struct {
var content string
func main() {
pa := &Address{"private", "Aartselaar","Belgium"}
pa := &Address{"private", "Aartselaar", "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}:
// using an encoder:
file, _ := os.OpenFile("vcard.gob", os.O_CREATE|os.O_WRONLY, 0666)
@@ -36,4 +36,3 @@ func main() {
log.Println("Error in encoding gob")
}
}

View File

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

View File

@@ -2,8 +2,8 @@
package main
import (
"fmt"
"crypto/sha1"
"fmt"
"io"
"log"
)
@@ -18,12 +18,13 @@ func main() {
hasher.Reset()
data := []byte("We shall overcome!")
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)
}
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]

View File

@@ -2,8 +2,8 @@
package main
import (
"fmt"
"encoding/json"
"fmt"
"log"
"os"
)
@@ -22,9 +22,9 @@ type VCard struct {
}
func main() {
pa := &Address{"private", "Aartselaar","Belgium"}
pa := &Address{"private", "Aartselaar", "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}:
// JSON format:
js, _ := json.Marshal(vc)

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,9 +1,9 @@
package main
import (
"bufio"
"fmt"
"os"
"bufio"
)
func main() {
@@ -19,23 +19,33 @@ func main() {
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!")
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")
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")
case "Philip\r\n", "Ivo\r\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
import (
"encoding/xml"
"fmt"
"strings"
"encoding/xml"
)
var t, token xml.Token
@@ -30,13 +30,14 @@ func main() {
fmt.Println("End of token")
case xml.CharData:
content := string([]byte(token))
fmt.Printf("This is the content: %v\n", content )
fmt.Printf("This is the content: %v\n", content)
// ...
default:
// ...
}
}
}
/* Output:
Token name: Person
Token name: FirstName

View File

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

View File

@@ -2,12 +2,12 @@
package main
import (
"fmt"
"even/even"
"fmt"
)
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))
}
}

View File

@@ -1,15 +1,16 @@
// exec.go
package main
import (
"fmt"
"os/exec"
"os"
"os/exec"
)
func main() {
// 1) os.StartProcess //
/*********************/
/* Linux: */
// 1) os.StartProcess //
/*********************/
/* Linux: */
env := os.Environ()
procAttr := &os.ProcAttr{
Env: env,
@@ -33,20 +34,20 @@ func main() {
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
*/
/* 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 ?
// 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 {
@@ -54,8 +55,7 @@ The process id is &{2054 0}total 2056
os.Exit(1)
}
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!

View File

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

View File

@@ -3,8 +3,8 @@ package parse
import (
"fmt"
"strings"
"strconv"
"strings"
)
// 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)
}()
for _ = range ch {
for range ch {
}
}
@@ -30,6 +30,6 @@ func BenchmarkChannelBuffered(b *testing.B) {
}
close(ch)
}()
for _ = range ch {
for range ch {
}
}

View File

@@ -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()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,8 +2,8 @@ package main
import (
"fmt"
"time"
"runtime"
"time"
)
func main() {
@@ -24,26 +24,24 @@ func main() {
}
func pump1(ch chan int) {
for i:=0; ; i++ {
ch <- i*2
for i := 0; ; i++ {
ch <- i * 2
}
}
func pump2(ch chan int) {
for i:=0; ; i++ {
ch <- i+5
for i := 0; ; i++ {
ch <- i + 5
}
}
func suck(ch1,ch2 chan int) {
func suck(ch1, ch2 chan int) {
for i := 0; ; i++ {
select {
case v := <- ch1:
case v := <-ch1:
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)
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -9,10 +9,9 @@ type nexter interface {
next() byte
}
func nextFew1(n nexter, num int) []byte {
var b []byte
for i:=0; i < num; i++ {
for i := 0; i < num; i++ {
b[i] = n.next()
}
return b
@@ -20,7 +19,7 @@ func nextFew1(n nexter, num int) []byte {
func nextFew2(n *nexter, num int) []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)
}
return b

View File

@@ -11,6 +11,7 @@ URL: <input type="text" name="url">
<input type="submit" value="Add">
</form>
`
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 == "" {

View File

@@ -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 == "" {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,17 +1,19 @@
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
// 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

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,7 @@
package main
var a = "G"
func main() {
n()
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\n", strings.HasPrefix(str, "Th"))
}
// 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())
}
}
/* 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 /

View File

@@ -21,9 +21,10 @@ func main() {
fmt.Printf("%s - ", val)
}
fmt.Println()
str3 := strings.Join(sl2,";")
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 -

View File

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

View File

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

View File

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

View File

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

View File

@@ -6,15 +6,16 @@ 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++ {
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++ {
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

View File

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

View File

@@ -7,7 +7,7 @@ func main() {
a := 1
goto TARGET // compile error
b := 9
TARGET:
TARGET:
b += a
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)))
}
}
/* Output:
The length of str is: 27
Character on position 0 is: G

View File

@@ -7,12 +7,12 @@ func main() {
doDBOperations()
}
func connectToDB () {
fmt.Println( "ok, connected to db" )
func connectToDB() {
fmt.Println("ok, connected to db")
}
func disconnectFromDB () {
fmt.Println( "ok, disconnected from db" )
func disconnectFromDB() {
fmt.Println("ok, disconnected from db")
}
func doDBOperations() {
@@ -25,6 +25,7 @@ func doDBOperations() {
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.
@@ -33,6 +34,3 @@ Oops! some crash or network error ...
Returning from function here!
ok, disconnected from db
*/

View File

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

View File

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

View File

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

View File

@@ -1,18 +1,19 @@
// filter_factory.go
package main
import "fmt"
type flt func (int) bool
type flt func(int) bool
type slice_split func([]int) ([]int, []int)
func isOdd(integer int) bool{
func isOdd(integer int) bool {
if integer%2 == 0 {
return false
}
return true
}
func isBiggerThan4(integer int) bool{
func isBiggerThan4(integer int) bool {
if integer > 4 {
return true
}
@@ -20,9 +21,9 @@ func isBiggerThan4(integer int) bool{
}
func filter_factory(f flt) slice_split {
return func(s []int) (yes, no []int){
for _, val := range s{
if f(val){
return func(s []int) (yes, no []int) {
for _, val := range s {
if f(val) {
yes = append(yes, val)
} else {
no = append(no, val)
@@ -32,8 +33,8 @@ func filter_factory(f flt) slice_split {
}
}
func main(){
s := []int {1, 2, 3, 4, 5, 7}
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)
@@ -44,6 +45,7 @@ func main(){
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]

View File

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

View File

@@ -1,5 +1,6 @@
// function_filter.go
package main
import "fmt"
type flt func(int) bool
@@ -33,14 +34,15 @@ func filter(sl []int, f flt) []int {
return res
}
func main(){
slice := []int {1, 2, 3, 4, 5, 7}
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]

View File

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

View File

@@ -9,12 +9,12 @@ 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 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

View File

@@ -1,4 +1,5 @@
package main
import "fmt"
func main() {
@@ -10,17 +11,18 @@ func main() {
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 b + 2
}
}
func Adder(a int) (func(b int) int) {
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

View File

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

View File

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

View File

@@ -5,13 +5,13 @@ 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}
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 {
if len(a) == 0 {
return 0
}
min := a[0]
@@ -22,6 +22,7 @@ func Min(a ...int) int {
}
return min
}
/*
The minimum is: 0
The minimum in the array arr is: 1

View File

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

View File

@@ -3,14 +3,14 @@ package main
import "fmt"
func main() {
sl_from := []int{1,2,3}
sl_to := make([]int,10)
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 := []int{1, 2, 3}
sl3 = append(sl3, 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