mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 03:55:28 +08:00
fix: coding style and file format for all example.
This commit is contained in:
@@ -9,8 +9,8 @@ type Log struct {
|
||||
}
|
||||
|
||||
type Customer struct {
|
||||
Name string
|
||||
log *Log
|
||||
Name string
|
||||
log *Log
|
||||
}
|
||||
|
||||
func main() {
|
||||
@@ -35,8 +35,9 @@ func (l *Log) String() string {
|
||||
}
|
||||
|
||||
func (c *Customer) Log() *Log {
|
||||
return c.log
|
||||
return c.log
|
||||
}
|
||||
|
||||
/* Output:
|
||||
1 - Yes we can!
|
||||
2 - After me the world will be a better place!
|
||||
|
@@ -9,8 +9,8 @@ type Log struct {
|
||||
}
|
||||
|
||||
type Customer struct {
|
||||
Name string
|
||||
Log
|
||||
Name string
|
||||
Log
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
@@ -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
|
@@ -12,5 +12,5 @@ func (v IntVector) Sum() (s int) {
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println(IntVector{1, 2, 3}.Sum()) // Output: 6
|
||||
fmt.Println(IntVector{1, 2, 3}.Sum()) // Output: 6
|
||||
}
|
||||
|
@@ -3,22 +3,23 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
"time"
|
||||
)
|
||||
|
||||
type myTime struct {
|
||||
time.Time //anonymous field
|
||||
time.Time //anonymous field
|
||||
}
|
||||
|
||||
func (t myTime) first3Chars() string {
|
||||
return t.Time.String()[0:3]
|
||||
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
|
||||
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
|
||||
|
@@ -23,5 +23,3 @@ func main() {
|
||||
func (tn *TwoInts) String() string {
|
||||
return "(" + strconv.Itoa(tn.a) + " / " + strconv.Itoa(tn.b) + ")"
|
||||
}
|
||||
|
||||
|
||||
|
@@ -6,17 +6,18 @@ import (
|
||||
)
|
||||
|
||||
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 main() {
|
||||
// A bare value
|
||||
var lst List
|
||||
lst.Append(1)
|
||||
fmt.Printf("%v (len: %d)\n", lst, lst.Len()) // [1] (len: 1)
|
||||
// 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)
|
||||
// A pointer value
|
||||
plst := new(List)
|
||||
plst.Append(2)
|
||||
fmt.Printf("%v (len: %d)\n", plst, lst.Len()) // &[2] (len: 1)
|
||||
}
|
||||
|
@@ -3,30 +3,31 @@ package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type Camera struct { }
|
||||
type Camera struct{}
|
||||
|
||||
func (c *Camera) TakeAPicture() string {
|
||||
return "Click"
|
||||
return "Click"
|
||||
}
|
||||
|
||||
type Phone struct { }
|
||||
type Phone struct{}
|
||||
|
||||
func (p *Phone ) Call() string {
|
||||
return "Ring Ring"
|
||||
func (p *Phone) Call() string {
|
||||
return "Ring Ring"
|
||||
}
|
||||
|
||||
// multiple inheritance
|
||||
type CameraPhone struct {
|
||||
Camera
|
||||
Phone
|
||||
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())
|
||||
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
|
||||
|
@@ -6,34 +6,35 @@ import (
|
||||
)
|
||||
|
||||
type Person struct {
|
||||
firstName string
|
||||
lastName string
|
||||
firstName string
|
||||
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
|
||||
|
@@ -1,8 +1,8 @@
|
||||
package person
|
||||
|
||||
type Person struct {
|
||||
firstName string
|
||||
lastName string
|
||||
firstName string
|
||||
lastName string
|
||||
}
|
||||
|
||||
func (p *Person) FirstName() string {
|
||||
@@ -10,8 +10,5 @@ func (p *Person) FirstName() string {
|
||||
}
|
||||
|
||||
func (p *Person) SetFirstName(newName string) {
|
||||
p.firstName = newName
|
||||
p.firstName = newName
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
@@ -6,22 +6,23 @@ import (
|
||||
)
|
||||
|
||||
type B struct {
|
||||
thing int
|
||||
thing int
|
||||
}
|
||||
|
||||
func (b *B) change() { b.thing = 1 }
|
||||
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())
|
||||
var b1 B // b1 is value
|
||||
b1.change()
|
||||
fmt.Println(b1.write())
|
||||
|
||||
b2 := new(B) // b2 is pointer
|
||||
b2.change()
|
||||
fmt.Println(b2.write())
|
||||
b2 := new(B) // b2 is pointer
|
||||
b2.change()
|
||||
fmt.Println(b2.write())
|
||||
}
|
||||
|
||||
/* Output:
|
||||
{1}
|
||||
{1}
|
||||
|
@@ -6,10 +6,10 @@ import (
|
||||
)
|
||||
|
||||
type number struct {
|
||||
f float32
|
||||
f float32
|
||||
}
|
||||
|
||||
type nr number // alias type
|
||||
type nr number // alias type
|
||||
|
||||
func main() {
|
||||
a := number{5.0}
|
||||
@@ -21,4 +21,5 @@ func main() {
|
||||
var c = number(b)
|
||||
fmt.Println(a, b, c)
|
||||
}
|
||||
|
||||
// output: {5} {5} {5}
|
||||
|
@@ -5,16 +5,16 @@ import (
|
||||
"reflect"
|
||||
)
|
||||
|
||||
type TagType struct { // tags
|
||||
field1 bool "An important answer"
|
||||
field2 string "The name of the thing"
|
||||
field3 int "How much there are"
|
||||
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)
|
||||
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
|
||||
|
@@ -3,13 +3,13 @@ package main
|
||||
import "fmt"
|
||||
|
||||
type innerS struct {
|
||||
in1 int
|
||||
in2 int
|
||||
in1 int
|
||||
in2 int
|
||||
}
|
||||
|
||||
type outerS struct {
|
||||
b int
|
||||
c float32
|
||||
b int
|
||||
c float32
|
||||
int // anonymous field
|
||||
innerS // anonymous field
|
||||
}
|
||||
|
@@ -3,9 +3,9 @@ package main
|
||||
import "fmt"
|
||||
|
||||
type struct1 struct {
|
||||
i1 int
|
||||
f1 float32
|
||||
str string
|
||||
i1 int
|
||||
f1 float32
|
||||
str string
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
@@ -1,8 +1,8 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"./person"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
@@ -5,26 +5,25 @@ import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
|
||||
type Any interface{}
|
||||
type Car struct {
|
||||
Model string
|
||||
Manufacturer string
|
||||
BuildYear int
|
||||
// ...
|
||||
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}
|
||||
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)
|
||||
return (car.Manufacturer == "BMW") && (car.BuildYear > 2010)
|
||||
})
|
||||
fmt.Println("AllCars: ", allCars)
|
||||
fmt.Println("New BMWs: ", allNewBMWs)
|
||||
@@ -33,58 +32,58 @@ func main() {
|
||||
sortedAppender, sortedCars := MakeSortedAppender(manufacturers)
|
||||
allCars.Process(sortedAppender)
|
||||
fmt.Println("Map sortedCars: ", sortedCars)
|
||||
BMWCount := len(sortedCars["BMW"])
|
||||
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)
|
||||
}
|
||||
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)
|
||||
cars := make([]*Car, 0)
|
||||
|
||||
cs.Process(func(c *Car) {
|
||||
if f(c) {
|
||||
cars = append(cars, c)
|
||||
}
|
||||
})
|
||||
return cars
|
||||
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
|
||||
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)
|
||||
// Prepare maps of sorted cars.
|
||||
sortedCars := make(map[string]Cars)
|
||||
|
||||
for _, m := range manufacturers {
|
||||
sortedCars[m] = make([]*Car, 0)
|
||||
}
|
||||
sortedCars["Default"] = make([]*Car, 0)
|
||||
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
|
||||
// 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:
|
||||
|
@@ -22,7 +22,7 @@ func (b *Bird) Quack() {
|
||||
fmt.Println("I am quacking!")
|
||||
}
|
||||
|
||||
func (b *Bird) Walk() {
|
||||
func (b *Bird) Walk() {
|
||||
fmt.Println("I am walking!")
|
||||
}
|
||||
|
||||
|
@@ -7,7 +7,7 @@ var str = "ABC"
|
||||
|
||||
type Person struct {
|
||||
name string
|
||||
age int
|
||||
age int
|
||||
}
|
||||
|
||||
type Any interface{}
|
||||
@@ -24,15 +24,15 @@ func main() {
|
||||
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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
@@ -29,4 +29,5 @@ func TypeSwitch() {
|
||||
func main() {
|
||||
TypeSwitch()
|
||||
}
|
||||
|
||||
// Output: any hello is a special String!
|
||||
|
@@ -27,4 +27,5 @@ func main() {
|
||||
areaIntf := sq1
|
||||
fmt.Printf("The square has area: %f\n", areaIntf.Area())
|
||||
}
|
||||
|
||||
// The square has area: 25.000000
|
||||
|
@@ -16,23 +16,24 @@ func (sq *Square) Area() float32 {
|
||||
}
|
||||
|
||||
type Rectangle struct {
|
||||
length, width float32
|
||||
length, width float32
|
||||
}
|
||||
|
||||
func (r Rectangle) Area() float32 {
|
||||
return r.length * r.width
|
||||
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())
|
||||
}
|
||||
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}
|
||||
@@ -40,6 +41,3 @@ Area of this shape is: 15
|
||||
Shape details: &{5}
|
||||
Area of this shape is: 25
|
||||
*/
|
||||
|
||||
|
||||
|
||||
|
@@ -6,43 +6,44 @@ import (
|
||||
)
|
||||
|
||||
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) }
|
||||
|
||||
type Appender interface {
|
||||
Append(int)
|
||||
Append(int)
|
||||
}
|
||||
|
||||
func CountInto(a Appender, start, end int) {
|
||||
for i := start; i <= end; i++ {
|
||||
a.Append(i)
|
||||
}
|
||||
for i := start; i <= end; i++ {
|
||||
a.Append(i)
|
||||
}
|
||||
}
|
||||
|
||||
type Lener interface {
|
||||
Len() int
|
||||
Len() int
|
||||
}
|
||||
|
||||
func LongEnough(l Lener) bool {
|
||||
return l.Len()*10 > 42
|
||||
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
|
||||
// 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")
|
||||
}
|
||||
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
|
||||
}
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
@@ -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}
|
||||
|
@@ -4,9 +4,9 @@ package main
|
||||
import "fmt"
|
||||
|
||||
type Node struct {
|
||||
le *Node
|
||||
data interface{}
|
||||
ri *Node
|
||||
le *Node
|
||||
data interface{}
|
||||
ri *Node
|
||||
}
|
||||
|
||||
func NewNode(left, right *Node) *Node {
|
||||
@@ -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
|
||||
|
@@ -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,18 +26,25 @@ 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)
|
||||
// more types
|
||||
default: os.Stdout.WriteString("???")
|
||||
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
|
||||
print(Day(1), "was", Celsius(18.36)) // Tuesday was 18.4 °C
|
||||
}
|
||||
|
||||
// Tuesday was 18.4 °C
|
@@ -20,6 +20,7 @@ func main() {
|
||||
y := v.Interface().(float64)
|
||||
fmt.Println(y)
|
||||
}
|
||||
|
||||
/* output:
|
||||
type: float64
|
||||
value: <float64 Value>
|
||||
|
@@ -22,6 +22,7 @@ func main() {
|
||||
fmt.Println(v.Interface())
|
||||
fmt.Println(v)
|
||||
}
|
||||
|
||||
/* Output:
|
||||
settability of v: false
|
||||
type of v: *float64
|
||||
|
@@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
type NotknownType struct {
|
||||
s1, s2, s3 string
|
||||
s1, s2, s3 string
|
||||
}
|
||||
|
||||
func (n NotknownType) String() string {
|
||||
@@ -15,19 +15,19 @@ 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>
|
||||
typ := reflect.TypeOf(secret) // main.NotknownType
|
||||
value := reflect.ValueOf(secret) // <main.NotknownType Value>
|
||||
typ := reflect.TypeOf(secret) // main.NotknownType
|
||||
// alternative:
|
||||
//typ := value.Type() // main.NotknownType
|
||||
fmt.Println(typ)
|
||||
knd := value.Kind() // struct
|
||||
knd := value.Kind() // struct
|
||||
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#")
|
||||
@@ -35,8 +35,9 @@ func main() {
|
||||
|
||||
// call the first method, which is String():
|
||||
results := value.Method(0).Call(nil)
|
||||
fmt.Println(results) // [Ada - Go - Oberon]
|
||||
fmt.Println(results) // [Ada - Go - Oberon]
|
||||
}
|
||||
|
||||
/* Output:
|
||||
main.NotknownType
|
||||
struct
|
||||
|
@@ -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
|
||||
|
@@ -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] }
|
||||
|
@@ -6,73 +6,72 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"./sort"
|
||||
"./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)
|
||||
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)
|
||||
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
|
||||
num int
|
||||
shortName string
|
||||
longName string
|
||||
}
|
||||
|
||||
type dayArray struct {
|
||||
data []*day
|
||||
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] }
|
||||
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")
|
||||
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()
|
||||
ints()
|
||||
strings()
|
||||
days()
|
||||
}
|
||||
|
||||
/* Output:
|
||||
|
@@ -2,11 +2,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
var r io.Reader
|
||||
|
@@ -43,8 +43,8 @@ package cgl
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"reflect"
|
||||
|
@@ -34,22 +34,22 @@ func main() {
|
||||
}
|
||||
// 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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -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))
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -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
|
||||
@@ -19,7 +19,7 @@ func main() {
|
||||
for i := 0; i < flag.NArg(); i++ {
|
||||
if i > 0 {
|
||||
s += " "
|
||||
if *NewLine { // -n is parsed, flag becomes true
|
||||
if *NewLine { // -n is parsed, flag becomes true
|
||||
s += Newline
|
||||
}
|
||||
}
|
||||
|
@@ -16,8 +16,8 @@ func main() {
|
||||
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")
|
||||
"Does the file exist?\n" +
|
||||
"Have you got acces to it?\n")
|
||||
return // exit the function on error
|
||||
}
|
||||
defer inputFile.Close()
|
||||
|
@@ -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()
|
||||
|
@@ -3,8 +3,8 @@ package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"encoding/gob"
|
||||
"fmt"
|
||||
"log"
|
||||
)
|
||||
|
||||
@@ -22,9 +22,9 @@ 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
|
||||
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.
|
||||
dec := gob.NewDecoder(&network) // Will read from network.
|
||||
// Encode (send) the value.
|
||||
err := enc.Encode(P{3, 4, 5, "Pythagoras"})
|
||||
if err != nil {
|
||||
@@ -38,4 +38,5 @@ func main() {
|
||||
}
|
||||
fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y)
|
||||
}
|
||||
|
||||
// Output: "Pythagoras": {3,4}
|
||||
|
@@ -8,24 +8,24 @@ import (
|
||||
)
|
||||
|
||||
type Address struct {
|
||||
Type string
|
||||
City string
|
||||
Country string
|
||||
Type string
|
||||
City string
|
||||
Country string
|
||||
}
|
||||
|
||||
type VCard struct {
|
||||
FirstName string
|
||||
LastName string
|
||||
Addresses []*Address
|
||||
Remark string
|
||||
FirstName string
|
||||
LastName string
|
||||
Addresses []*Address
|
||||
Remark string
|
||||
}
|
||||
|
||||
var content string
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -2,10 +2,10 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"bufio"
|
||||
"os"
|
||||
"compress/gzip"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
@@ -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]
|
||||
|
@@ -2,29 +2,29 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
type Address struct {
|
||||
Type string
|
||||
City string
|
||||
Country string
|
||||
Type string
|
||||
City string
|
||||
Country string
|
||||
}
|
||||
|
||||
type VCard struct {
|
||||
FirstName string
|
||||
LastName string
|
||||
Addresses []*Address
|
||||
Remark string
|
||||
FirstName string
|
||||
LastName string
|
||||
Addresses []*Address
|
||||
Remark 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}:
|
||||
// JSON format:
|
||||
js, _ := json.Marshal(vc)
|
||||
|
@@ -32,6 +32,7 @@ func main() {
|
||||
fmt.Printf("From XML: %#v\n", tx)
|
||||
|
||||
}
|
||||
|
||||
/* Output with
|
||||
type thing struct {
|
||||
Field1 int
|
||||
|
@@ -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]
|
||||
|
@@ -21,10 +21,8 @@ func main() {
|
||||
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)
|
||||
for line, _, err := r.ReadLine(); err != io.EOF; line, _, err = r.ReadLine() {
|
||||
fmt.Printf("Lines: %v (error %v)\n", string(line), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -7,10 +7,10 @@ import (
|
||||
|
||||
var (
|
||||
firstName, lastName, s string
|
||||
i int
|
||||
f float32
|
||||
input = "56.12 / 5212 / Go"
|
||||
format = "%f / %d / %s"
|
||||
i int
|
||||
f float32
|
||||
input = "56.12 / 5212 / Go"
|
||||
format = "%f / %d / %s"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
@@ -2,17 +2,17 @@
|
||||
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
|
||||
inputReader = bufio.NewReader(os.Stdin) // reader for input
|
||||
fmt.Println("Please enter some input: ")
|
||||
input, err = inputReader.ReadString('\n')
|
||||
|
||||
|
@@ -1,41 +1,51 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"bufio"
|
||||
)
|
||||
|
||||
func main() {
|
||||
inputReader := bufio.NewReader(os.Stdin)
|
||||
fmt.Println("Please enter your name:")
|
||||
input, err := inputReader.ReadString('\n')
|
||||
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
|
||||
}
|
||||
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!")
|
||||
}
|
||||
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 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")
|
||||
}
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
@@ -2,13 +2,13 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"strings"
|
||||
"encoding/xml"
|
||||
)
|
||||
|
||||
var t, token xml.Token
|
||||
var err error
|
||||
var t, token xml.Token
|
||||
var err error
|
||||
|
||||
func main() {
|
||||
input := "<Person><FirstName>Laura</FirstName><LastName>Lynn</LastName></Person>"
|
||||
@@ -17,26 +17,27 @@ func main() {
|
||||
|
||||
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:
|
||||
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
|
||||
|
@@ -11,4 +11,5 @@ var errNotFound error = errors.New("Not found error")
|
||||
func main() {
|
||||
fmt.Printf("error: %v", errNotFound)
|
||||
}
|
||||
|
||||
// error: Not found error
|
@@ -1,10 +1,10 @@
|
||||
// even.go
|
||||
package even
|
||||
|
||||
func Even(i int) bool { // Exported function
|
||||
func Even(i int) bool { // Exported function
|
||||
return i%2 == 0
|
||||
}
|
||||
|
||||
func Odd(i int) bool { // Exported function
|
||||
func Odd(i int) bool { // Exported function
|
||||
return i%2 != 0
|
||||
}
|
||||
|
@@ -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))
|
||||
}
|
||||
}
|
||||
|
@@ -1,61 +1,61 @@
|
||||
// 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,
|
||||
Files: []*os.File{
|
||||
os.Stdin,
|
||||
os.Stdout,
|
||||
os.Stderr,
|
||||
},
|
||||
}
|
||||
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("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("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
|
||||
*/
|
||||
/* 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
|
||||
// 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] [] <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!
|
||||
|
||||
|
||||
|
@@ -2,29 +2,30 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"./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",
|
||||
"",
|
||||
}
|
||||
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)
|
||||
}
|
||||
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]
|
||||
|
@@ -3,49 +3,49 @@ package parse
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"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.
|
||||
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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
}()
|
||||
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
|
||||
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
|
||||
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
|
||||
}
|
||||
|
@@ -7,7 +7,7 @@ import (
|
||||
|
||||
func main() {
|
||||
fmt.Println(" sync", testing.Benchmark(BenchmarkChannelSync).String())
|
||||
fmt.Println("buffered", testing.Benchmark(BenchmarkChannelBuffered).String())
|
||||
fmt.Println("buffered", testing.Benchmark(BenchmarkChannelBuffered).String())
|
||||
}
|
||||
|
||||
func BenchmarkChannelSync(b *testing.B) {
|
||||
@@ -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 {
|
||||
}
|
||||
}
|
||||
|
@@ -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()
|
||||
|
@@ -13,4 +13,3 @@ func pump(ch chan int) {
|
||||
ch <- i
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -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:
|
||||
|
@@ -43,6 +43,7 @@ func BuildLazyIntEvaluator(evalFunc EvalFunc, initState Any) func() int {
|
||||
return ef().(int)
|
||||
}
|
||||
}
|
||||
|
||||
/* Output:
|
||||
0th even: 0
|
||||
1th even: 2
|
||||
|
@@ -30,4 +30,5 @@ func getData(ch chan string) {
|
||||
fmt.Printf("%s ", input)
|
||||
}
|
||||
}
|
||||
|
||||
// Washington Tripoli London Beijing Tokio
|
@@ -26,4 +26,5 @@ func getData(ch chan string) {
|
||||
fmt.Printf("%s ", input)
|
||||
}
|
||||
}
|
||||
|
||||
// Washington Tripoli London Beijing Tokio
|
@@ -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:
|
||||
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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@@ -8,19 +8,19 @@ import (
|
||||
var resume chan int
|
||||
|
||||
func integers() chan int {
|
||||
yield := make (chan int)
|
||||
count := 0
|
||||
go func () {
|
||||
for {
|
||||
yield <- count
|
||||
count++
|
||||
}
|
||||
} ()
|
||||
return yield
|
||||
yield := make(chan int)
|
||||
count := 0
|
||||
go func() {
|
||||
for {
|
||||
yield <- count
|
||||
count++
|
||||
}
|
||||
}()
|
||||
return yield
|
||||
}
|
||||
|
||||
func generateInteger() int {
|
||||
return <-resume
|
||||
return <-resume
|
||||
}
|
||||
func main() {
|
||||
resume = integers()
|
||||
|
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
const MAXREQS = 50
|
||||
|
||||
var sem = make(chan int, MAXREQS)
|
||||
|
||||
type Request struct {
|
||||
@@ -13,16 +14,16 @@ func process(r *Request) {
|
||||
}
|
||||
|
||||
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
|
||||
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)
|
||||
}
|
||||
for {
|
||||
request := <-service
|
||||
go handle(request)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
@@ -19,10 +19,10 @@ func run(op binOp, req *Request) {
|
||||
func server(op binOp, service chan *Request, quit chan bool) {
|
||||
for {
|
||||
select {
|
||||
case req := <-service:
|
||||
go run(op, req)
|
||||
case <-quit:
|
||||
return
|
||||
case req := <-service:
|
||||
go run(op, req)
|
||||
case <-quit:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -22,6 +22,7 @@ func main() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Output:
|
||||
.
|
||||
.
|
||||
|
@@ -10,10 +10,10 @@ var values = [5]int{10, 11, 12, 13, 14}
|
||||
|
||||
func main() {
|
||||
// version A:
|
||||
for ix := range values { // ix is index!
|
||||
for ix := range values { // ix is index!
|
||||
func() {
|
||||
fmt.Print(ix, " ")
|
||||
}() // call closure, prints each index
|
||||
}() // call closure, prints each index
|
||||
}
|
||||
fmt.Println()
|
||||
// version B: same as A, but call closure as a goroutine
|
||||
@@ -25,20 +25,21 @@ func main() {
|
||||
time.Sleep(1e9)
|
||||
// version C: the right way
|
||||
for ix := range values {
|
||||
go func(ix interface{}) {
|
||||
fmt.Print(ix, " ")
|
||||
}(ix)
|
||||
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, " ")
|
||||
}()
|
||||
val := values[ix]
|
||||
go func() {
|
||||
fmt.Print(val, " ")
|
||||
}()
|
||||
}
|
||||
time.Sleep(1e9)
|
||||
}
|
||||
|
||||
/* Output:
|
||||
0 1 2 3 4
|
||||
4 4 4 4 4
|
||||
|
@@ -6,13 +6,12 @@ import (
|
||||
)
|
||||
|
||||
type nexter interface {
|
||||
next() byte
|
||||
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
|
||||
|
@@ -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 == "" {
|
||||
|
@@ -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 {
|
||||
|
@@ -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 == "" {
|
||||
|
@@ -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 {
|
||||
|
@@ -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 {
|
||||
@@ -103,7 +103,7 @@ func (s *URLStore) saveLoop(filename string) {
|
||||
// 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)
|
||||
}
|
||||
|
@@ -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 {
|
||||
@@ -95,7 +95,7 @@ func (s *URLStore) saveLoop(filename string) {
|
||||
defer f.Close()
|
||||
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)
|
||||
}
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -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 {
|
||||
|
@@ -4,4 +4,3 @@ package main
|
||||
func main() {
|
||||
println("Hello", "world")
|
||||
}
|
||||
|
||||
|
@@ -8,5 +8,6 @@ import (
|
||||
func main() {
|
||||
fmt.Printf("%s", runtime.Version())
|
||||
}
|
||||
|
||||
// Output:
|
||||
// go1.0.3 or go 1.1
|
||||
|
@@ -1,14 +1,14 @@
|
||||
package hello
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func init() {
|
||||
http.HandleFunc("/", handler)
|
||||
http.HandleFunc("/", handler)
|
||||
}
|
||||
|
||||
func handler(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, "Hello, world!")
|
||||
fmt.Fprint(w, "Hello, world!")
|
||||
}
|
||||
|
@@ -1,28 +1,28 @@
|
||||
package hello
|
||||
|
||||
import (
|
||||
"appengine"
|
||||
"appengine/user"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"appengine"
|
||||
"appengine/user"
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func init() {
|
||||
http.HandleFunc("/", handler)
|
||||
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)
|
||||
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)
|
||||
}
|
||||
|
@@ -1,9 +1,9 @@
|
||||
package hello
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"template"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"template"
|
||||
)
|
||||
|
||||
const guestbookForm = `
|
||||
@@ -24,23 +24,23 @@ const signTemplateHTML = `
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
|
||||
var signTemplate = template.Must(template.New("sign").Parse(signTemplateHTML))
|
||||
|
||||
func init() {
|
||||
http.HandleFunc("/", root)
|
||||
http.HandleFunc("/sign", sign)
|
||||
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)
|
||||
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)
|
||||
}
|
||||
err := signTemplate.Execute(w, r.FormValue("content"))
|
||||
if err != nil {
|
||||
http.Error(w, err.String(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -28,6 +28,7 @@ const guestbookTemplateHTML = `
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
|
||||
var guestbookTemplate = template.Must(template.New("book").Parse(guestbookTemplateHTML))
|
||||
|
||||
type Greeting struct {
|
||||
|
@@ -13,4 +13,3 @@ func init() {
|
||||
func handle(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, "<html><body>Hello, World! 세상아 안녕!! </body></html>")
|
||||
}
|
||||
|
||||
|
@@ -5,9 +5,9 @@ package rand
|
||||
import "C"
|
||||
|
||||
func Random() int {
|
||||
return int(C.random())
|
||||
return int(C.random())
|
||||
}
|
||||
|
||||
func Seed(i int) {
|
||||
C.srandom(C.uint(i))
|
||||
C.srandom(C.uint(i))
|
||||
}
|
||||
|
@@ -7,7 +7,7 @@ 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))
|
||||
cs := C.CString(s)
|
||||
defer C.free(unsafe.Pointer(cs))
|
||||
C.fputs(cs, (*C.FILE)(C.stdout))
|
||||
}
|
||||
|
@@ -1,6 +1,6 @@
|
||||
package main
|
||||
|
||||
import fm "fmt" // alias
|
||||
import fm "fmt" // alias
|
||||
|
||||
func main() {
|
||||
fm.Println("hello, world")
|
||||
|
@@ -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
|
||||
|
@@ -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 - β -
|
||||
|
@@ -1,5 +1,7 @@
|
||||
package main
|
||||
|
||||
var a string
|
||||
|
||||
func main() {
|
||||
a = "G"
|
||||
print(a)
|
||||
|
@@ -1,5 +1,7 @@
|
||||
package main
|
||||
|
||||
var a = "G"
|
||||
|
||||
func main() {
|
||||
n()
|
||||
m()
|
||||
|
@@ -1,5 +1,7 @@
|
||||
package main
|
||||
|
||||
var a = "G"
|
||||
|
||||
func main() {
|
||||
n()
|
||||
m()
|
||||
|
@@ -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
|
@@ -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 /
|
||||
|
@@ -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 -
|
||||
|
@@ -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
|
||||
|
@@ -9,18 +9,18 @@ var week time.Duration
|
||||
|
||||
func main() {
|
||||
t := time.Now()
|
||||
fmt.Println(t) // Wed Dec 21 09:52:14 +0100 RST 2011
|
||||
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 = 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
|
||||
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(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
|
||||
|
@@ -4,6 +4,6 @@ func main() {
|
||||
var a int
|
||||
var b int32
|
||||
a = 15
|
||||
b = a + a // compiler error
|
||||
b = b + 5 // ok: 5 is a constant
|
||||
b = a + a // compiler error
|
||||
b = b + 5 // ok: 5 is a constant
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user