mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 04:48:29 +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 {
|
type Customer struct {
|
||||||
Name string
|
Name string
|
||||||
log *Log
|
log *Log
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -35,8 +35,9 @@ func (l *Log) String() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Customer) Log() *Log {
|
func (c *Customer) Log() *Log {
|
||||||
return c.log
|
return c.log
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
1 - Yes we can!
|
1 - Yes we can!
|
||||||
2 - After me the world will be a better place!
|
2 - After me the world will be a better place!
|
||||||
|
@@ -9,8 +9,8 @@ type Log struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Customer struct {
|
type Customer struct {
|
||||||
Name string
|
Name string
|
||||||
Log
|
Log
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
@@ -1,8 +1,8 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"./struct_pack/structPack"
|
"./struct_pack/structPack"
|
||||||
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -12,5 +12,6 @@ func main() {
|
|||||||
fmt.Printf("Mi1 = %d\n", struct1.Mi1)
|
fmt.Printf("Mi1 = %d\n", struct1.Mi1)
|
||||||
fmt.Printf("Mf1 = %f\n", struct1.Mf1)
|
fmt.Printf("Mf1 = %f\n", struct1.Mf1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mi1 = 10
|
// Mi1 = 10
|
||||||
// Mf1 = 16.000000
|
// Mf1 = 16.000000
|
@@ -12,5 +12,5 @@ func (v IntVector) Sum() (s int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
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 (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type myTime struct {
|
type myTime struct {
|
||||||
time.Time //anonymous field
|
time.Time //anonymous field
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t myTime) first3Chars() string {
|
func (t myTime) first3Chars() string {
|
||||||
return t.Time.String()[0:3]
|
return t.Time.String()[0:3]
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
m := myTime{time.Now()}
|
m := myTime{time.Now()}
|
||||||
fmt.Println("Full time now:", m.String()) //calling existing String method on anonymous Time field
|
fmt.Println("Full time now:", m.String()) //calling existing String method on anonymous Time field
|
||||||
fmt.Println("First 3 chars:", m.first3Chars()) //calling myTime.first3Chars
|
fmt.Println("First 3 chars:", m.first3Chars()) //calling myTime.first3Chars
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
Full time now: Mon Oct 24 15:34:54 Romance Daylight Time 2011
|
Full time now: Mon Oct 24 15:34:54 Romance Daylight Time 2011
|
||||||
First 3 chars: Mon
|
First 3 chars: Mon
|
||||||
|
@@ -23,5 +23,3 @@ func main() {
|
|||||||
func (tn *TwoInts) String() string {
|
func (tn *TwoInts) String() string {
|
||||||
return "(" + strconv.Itoa(tn.a) + " / " + strconv.Itoa(tn.b) + ")"
|
return "(" + strconv.Itoa(tn.a) + " / " + strconv.Itoa(tn.b) + ")"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@@ -6,17 +6,18 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type List []int
|
type List []int
|
||||||
func (l List) Len() int { return len(l) }
|
|
||||||
|
func (l List) Len() int { return len(l) }
|
||||||
func (l *List) Append(val int) { *l = append(*l, val) }
|
func (l *List) Append(val int) { *l = append(*l, val) }
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// A bare value
|
// A bare value
|
||||||
var lst List
|
var lst List
|
||||||
lst.Append(1)
|
lst.Append(1)
|
||||||
fmt.Printf("%v (len: %d)\n", lst, lst.Len()) // [1] (len: 1)
|
fmt.Printf("%v (len: %d)\n", lst, lst.Len()) // [1] (len: 1)
|
||||||
|
|
||||||
// A pointer value
|
// A pointer value
|
||||||
plst := new(List)
|
plst := new(List)
|
||||||
plst.Append(2)
|
plst.Append(2)
|
||||||
fmt.Printf("%v (len: %d)\n", plst, lst.Len()) // &[2] (len: 1)
|
fmt.Printf("%v (len: %d)\n", plst, lst.Len()) // &[2] (len: 1)
|
||||||
}
|
}
|
||||||
|
@@ -3,30 +3,31 @@ package main
|
|||||||
|
|
||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
type Camera struct { }
|
type Camera struct{}
|
||||||
|
|
||||||
func (c *Camera) TakeAPicture() string {
|
func (c *Camera) TakeAPicture() string {
|
||||||
return "Click"
|
return "Click"
|
||||||
}
|
}
|
||||||
|
|
||||||
type Phone struct { }
|
type Phone struct{}
|
||||||
|
|
||||||
func (p *Phone ) Call() string {
|
func (p *Phone) Call() string {
|
||||||
return "Ring Ring"
|
return "Ring Ring"
|
||||||
}
|
}
|
||||||
|
|
||||||
// multiple inheritance
|
// multiple inheritance
|
||||||
type CameraPhone struct {
|
type CameraPhone struct {
|
||||||
Camera
|
Camera
|
||||||
Phone
|
Phone
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
cp := new(CameraPhone)
|
cp := new(CameraPhone)
|
||||||
fmt.Println("Our new CameraPhone exhibits multiple behaviors ...")
|
fmt.Println("Our new CameraPhone exhibits multiple behaviors ...")
|
||||||
fmt.Println("It exhibits behavior of a Camera: ", cp.TakeAPicture())
|
fmt.Println("It exhibits behavior of a Camera: ", cp.TakeAPicture())
|
||||||
fmt.Println("It works like a Phone too: ", cp.Call())
|
fmt.Println("It works like a Phone too: ", cp.Call())
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
Our new CameraPhone exhibits multiple behaviors ...
|
Our new CameraPhone exhibits multiple behaviors ...
|
||||||
It exhibits behavior of a Camera: Click
|
It exhibits behavior of a Camera: Click
|
||||||
|
@@ -6,34 +6,35 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Person struct {
|
type Person struct {
|
||||||
firstName string
|
firstName string
|
||||||
lastName string
|
lastName string
|
||||||
}
|
}
|
||||||
|
|
||||||
func upPerson (p *Person) {
|
func upPerson(p *Person) {
|
||||||
p.firstName = strings.ToUpper(p.firstName)
|
p.firstName = strings.ToUpper(p.firstName)
|
||||||
p.lastName = strings.ToUpper(p.lastName)
|
p.lastName = strings.ToUpper(p.lastName)
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// 1- struct as a value type:
|
// 1- struct as a value type:
|
||||||
var pers1 Person
|
var pers1 Person
|
||||||
pers1.firstName = "Chris"
|
pers1.firstName = "Chris"
|
||||||
pers1.lastName = "Woodward"
|
pers1.lastName = "Woodward"
|
||||||
upPerson(&pers1)
|
upPerson(&pers1)
|
||||||
fmt.Printf("The name of the person is %s %s\n", pers1.firstName, pers1.lastName)
|
fmt.Printf("The name of the person is %s %s\n", pers1.firstName, pers1.lastName)
|
||||||
// 2 - struct as a pointer:
|
// 2 - struct as a pointer:
|
||||||
pers2 := new(Person)
|
pers2 := new(Person)
|
||||||
pers2.firstName = "Chris"
|
pers2.firstName = "Chris"
|
||||||
pers2.lastName = "Woodward"
|
pers2.lastName = "Woodward"
|
||||||
(*pers2).lastName = "Woodward"
|
(*pers2).lastName = "Woodward"
|
||||||
upPerson(pers2)
|
upPerson(pers2)
|
||||||
fmt.Printf("The name of the person is %s %s\n", pers2.firstName, pers2.lastName)
|
fmt.Printf("The name of the person is %s %s\n", pers2.firstName, pers2.lastName)
|
||||||
// 3 - struct as a literal:
|
// 3 - struct as a literal:
|
||||||
pers3 := &Person{"Chris","Woodward"}
|
pers3 := &Person{"Chris", "Woodward"}
|
||||||
upPerson(pers3)
|
upPerson(pers3)
|
||||||
fmt.Printf("The name of the person is %s %s\n", pers3.firstName, pers3.lastName)
|
fmt.Printf("The name of the person is %s %s\n", pers3.firstName, pers3.lastName)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
The name of the person is CHRIS WOODWARD
|
The name of the person is CHRIS WOODWARD
|
||||||
The name of the person is CHRIS WOODWARD
|
The name of the person is CHRIS WOODWARD
|
||||||
|
@@ -1,8 +1,8 @@
|
|||||||
package person
|
package person
|
||||||
|
|
||||||
type Person struct {
|
type Person struct {
|
||||||
firstName string
|
firstName string
|
||||||
lastName string
|
lastName string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Person) FirstName() string {
|
func (p *Person) FirstName() string {
|
||||||
@@ -10,8 +10,5 @@ func (p *Person) FirstName() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *Person) SetFirstName(newName string) {
|
func (p *Person) SetFirstName(newName string) {
|
||||||
p.firstName = newName
|
p.firstName = newName
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@@ -6,22 +6,23 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type B struct {
|
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 (b B) write() string { return fmt.Sprint(b) }
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var b1 B // b1 is value
|
var b1 B // b1 is value
|
||||||
b1.change()
|
b1.change()
|
||||||
fmt.Println(b1.write())
|
fmt.Println(b1.write())
|
||||||
|
|
||||||
b2 := new(B) // b2 is pointer
|
b2 := new(B) // b2 is pointer
|
||||||
b2.change()
|
b2.change()
|
||||||
fmt.Println(b2.write())
|
fmt.Println(b2.write())
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
{1}
|
{1}
|
||||||
{1}
|
{1}
|
||||||
|
@@ -6,10 +6,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type number struct {
|
type number struct {
|
||||||
f float32
|
f float32
|
||||||
}
|
}
|
||||||
|
|
||||||
type nr number // alias type
|
type nr number // alias type
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
a := number{5.0}
|
a := number{5.0}
|
||||||
@@ -21,4 +21,5 @@ func main() {
|
|||||||
var c = number(b)
|
var c = number(b)
|
||||||
fmt.Println(a, b, c)
|
fmt.Println(a, b, c)
|
||||||
}
|
}
|
||||||
|
|
||||||
// output: {5} {5} {5}
|
// output: {5} {5} {5}
|
||||||
|
@@ -5,16 +5,16 @@ import (
|
|||||||
"reflect"
|
"reflect"
|
||||||
)
|
)
|
||||||
|
|
||||||
type TagType struct { // tags
|
type TagType struct { // tags
|
||||||
field1 bool "An important answer"
|
field1 bool "An important answer"
|
||||||
field2 string "The name of the thing"
|
field2 string "The name of the thing"
|
||||||
field3 int "How much there are"
|
field3 int "How much there are"
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
tt := TagType{true, "Barak Obama", 1}
|
tt := TagType{true, "Barak Obama", 1}
|
||||||
for i:= 0; i < 3; i++ {
|
for i := 0; i < 3; i++ {
|
||||||
refTag(tt, i)
|
refTag(tt, i)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,6 +23,7 @@ func refTag(tt TagType, ix int) {
|
|||||||
ixField := ttType.Field(ix)
|
ixField := ttType.Field(ix)
|
||||||
fmt.Printf("%v\n", ixField.Tag)
|
fmt.Printf("%v\n", ixField.Tag)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
An important answer
|
An important answer
|
||||||
The name of the thing
|
The name of the thing
|
||||||
|
@@ -3,13 +3,13 @@ package main
|
|||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
type innerS struct {
|
type innerS struct {
|
||||||
in1 int
|
in1 int
|
||||||
in2 int
|
in2 int
|
||||||
}
|
}
|
||||||
|
|
||||||
type outerS struct {
|
type outerS struct {
|
||||||
b int
|
b int
|
||||||
c float32
|
c float32
|
||||||
int // anonymous field
|
int // anonymous field
|
||||||
innerS // anonymous field
|
innerS // anonymous field
|
||||||
}
|
}
|
||||||
|
@@ -3,9 +3,9 @@ package main
|
|||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
type struct1 struct {
|
type struct1 struct {
|
||||||
i1 int
|
i1 int
|
||||||
f1 float32
|
f1 float32
|
||||||
str string
|
str string
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
@@ -1,8 +1,8 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"./person"
|
"./person"
|
||||||
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
@@ -5,26 +5,25 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
type Any interface{}
|
type Any interface{}
|
||||||
type Car struct {
|
type Car struct {
|
||||||
Model string
|
Model string
|
||||||
Manufacturer string
|
Manufacturer string
|
||||||
BuildYear int
|
BuildYear int
|
||||||
// ...
|
// ...
|
||||||
}
|
}
|
||||||
type Cars []*Car
|
type Cars []*Car
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// make some cars:
|
// make some cars:
|
||||||
ford := &Car{"Fiesta","Ford", 2008}
|
ford := &Car{"Fiesta", "Ford", 2008}
|
||||||
bmw := &Car{"XL 450", "BMW", 2011}
|
bmw := &Car{"XL 450", "BMW", 2011}
|
||||||
merc := &Car{"D600", "Mercedes", 2009}
|
merc := &Car{"D600", "Mercedes", 2009}
|
||||||
bmw2 := &Car{"X 800", "BMW", 2008}
|
bmw2 := &Car{"X 800", "BMW", 2008}
|
||||||
// query:
|
// query:
|
||||||
allCars := Cars([]*Car{ford, bmw, merc, bmw2})
|
allCars := Cars([]*Car{ford, bmw, merc, bmw2})
|
||||||
allNewBMWs := allCars.FindAll(func(car *Car) bool {
|
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("AllCars: ", allCars)
|
||||||
fmt.Println("New BMWs: ", allNewBMWs)
|
fmt.Println("New BMWs: ", allNewBMWs)
|
||||||
@@ -33,58 +32,58 @@ func main() {
|
|||||||
sortedAppender, sortedCars := MakeSortedAppender(manufacturers)
|
sortedAppender, sortedCars := MakeSortedAppender(manufacturers)
|
||||||
allCars.Process(sortedAppender)
|
allCars.Process(sortedAppender)
|
||||||
fmt.Println("Map sortedCars: ", sortedCars)
|
fmt.Println("Map sortedCars: ", sortedCars)
|
||||||
BMWCount := len(sortedCars["BMW"])
|
BMWCount := len(sortedCars["BMW"])
|
||||||
fmt.Println("We have ", BMWCount, " BMWs")
|
fmt.Println("We have ", BMWCount, " BMWs")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Process all cars with the given function f:
|
// Process all cars with the given function f:
|
||||||
func (cs Cars) Process(f func(car *Car)) {
|
func (cs Cars) Process(f func(car *Car)) {
|
||||||
for _, c := range cs {
|
for _, c := range cs {
|
||||||
f(c)
|
f(c)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find all cars matching a given criteria.
|
// Find all cars matching a given criteria.
|
||||||
func (cs Cars) FindAll(f func(car *Car) bool) Cars {
|
func (cs Cars) FindAll(f func(car *Car) bool) Cars {
|
||||||
cars := make([]*Car, 0)
|
cars := make([]*Car, 0)
|
||||||
|
|
||||||
cs.Process(func(c *Car) {
|
cs.Process(func(c *Car) {
|
||||||
if f(c) {
|
if f(c) {
|
||||||
cars = append(cars, c)
|
cars = append(cars, c)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
return cars
|
return cars
|
||||||
}
|
}
|
||||||
|
|
||||||
// Process cars and create new data.
|
// Process cars and create new data.
|
||||||
func (cs Cars) Map(f func(car *Car) Any) []Any {
|
func (cs Cars) Map(f func(car *Car) Any) []Any {
|
||||||
result := make([]Any, 0)
|
result := make([]Any, 0)
|
||||||
ix := 0
|
ix := 0
|
||||||
cs.Process(func(c *Car) {
|
cs.Process(func(c *Car) {
|
||||||
result[ix] = f(c)
|
result[ix] = f(c)
|
||||||
ix++
|
ix++
|
||||||
})
|
})
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
func MakeSortedAppender(manufacturers []string) (func(car *Car), map[string]Cars) {
|
func MakeSortedAppender(manufacturers []string) (func(car *Car), map[string]Cars) {
|
||||||
// Prepare maps of sorted cars.
|
// Prepare maps of sorted cars.
|
||||||
sortedCars := make(map[string]Cars)
|
sortedCars := make(map[string]Cars)
|
||||||
|
|
||||||
for _, m := range manufacturers {
|
for _, m := range manufacturers {
|
||||||
sortedCars[m] = make([]*Car, 0)
|
sortedCars[m] = make([]*Car, 0)
|
||||||
}
|
}
|
||||||
sortedCars["Default"] = make([]*Car, 0)
|
sortedCars["Default"] = make([]*Car, 0)
|
||||||
|
|
||||||
// Prepare appender function:
|
// Prepare appender function:
|
||||||
appender := func(c *Car) {
|
appender := func(c *Car) {
|
||||||
if _, ok := sortedCars[c.Manufacturer]; ok {
|
if _, ok := sortedCars[c.Manufacturer]; ok {
|
||||||
sortedCars[c.Manufacturer] = append(sortedCars[c.Manufacturer], c)
|
sortedCars[c.Manufacturer] = append(sortedCars[c.Manufacturer], c)
|
||||||
} else {
|
} else {
|
||||||
sortedCars["Default"] = append(sortedCars["Default"], c)
|
sortedCars["Default"] = append(sortedCars["Default"], c)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return appender, sortedCars
|
return appender, sortedCars
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
|
@@ -22,7 +22,7 @@ func (b *Bird) Quack() {
|
|||||||
fmt.Println("I am quacking!")
|
fmt.Println("I am quacking!")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Bird) Walk() {
|
func (b *Bird) Walk() {
|
||||||
fmt.Println("I am walking!")
|
fmt.Println("I am walking!")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -7,7 +7,7 @@ var str = "ABC"
|
|||||||
|
|
||||||
type Person struct {
|
type Person struct {
|
||||||
name string
|
name string
|
||||||
age int
|
age int
|
||||||
}
|
}
|
||||||
|
|
||||||
type Any interface{}
|
type Any interface{}
|
||||||
@@ -24,15 +24,15 @@ func main() {
|
|||||||
val = pers1
|
val = pers1
|
||||||
fmt.Printf("val has the value: %v\n", val)
|
fmt.Printf("val has the value: %v\n", val)
|
||||||
switch t := val.(type) {
|
switch t := val.(type) {
|
||||||
case int:
|
case int:
|
||||||
fmt.Printf("Type int %T\n", t)
|
fmt.Printf("Type int %T\n", t)
|
||||||
case string:
|
case string:
|
||||||
fmt.Printf("Type string %T\n", t)
|
fmt.Printf("Type string %T\n", t)
|
||||||
case bool:
|
case bool:
|
||||||
fmt.Printf("Type boolean %T\n", t)
|
fmt.Printf("Type boolean %T\n", t)
|
||||||
case *Person:
|
case *Person:
|
||||||
fmt.Printf("Type pointer to Person %T\n", *t)
|
fmt.Printf("Type pointer to Person %T\n", *t)
|
||||||
default:
|
default:
|
||||||
fmt.Printf("Unexpected type %T", t)
|
fmt.Printf("Unexpected type %T", t)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -29,4 +29,5 @@ func TypeSwitch() {
|
|||||||
func main() {
|
func main() {
|
||||||
TypeSwitch()
|
TypeSwitch()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Output: any hello is a special String!
|
// Output: any hello is a special String!
|
||||||
|
@@ -27,4 +27,5 @@ func main() {
|
|||||||
areaIntf := sq1
|
areaIntf := sq1
|
||||||
fmt.Printf("The square has area: %f\n", areaIntf.Area())
|
fmt.Printf("The square has area: %f\n", areaIntf.Area())
|
||||||
}
|
}
|
||||||
|
|
||||||
// The square has area: 25.000000
|
// The square has area: 25.000000
|
||||||
|
@@ -16,23 +16,24 @@ func (sq *Square) Area() float32 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Rectangle struct {
|
type Rectangle struct {
|
||||||
length, width float32
|
length, width float32
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Rectangle) Area() float32 {
|
func (r Rectangle) Area() float32 {
|
||||||
return r.length * r.width
|
return r.length * r.width
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
r := Rectangle{5, 3} // Area() of Rectangle needs a value
|
r := Rectangle{5, 3} // Area() of Rectangle needs a value
|
||||||
q := &Square{5} // Area() of Square needs a pointer
|
q := &Square{5} // Area() of Square needs a pointer
|
||||||
shapes := []Shaper{r, q}
|
shapes := []Shaper{r, q}
|
||||||
fmt.Println("Looping through shapes for area ...")
|
fmt.Println("Looping through shapes for area ...")
|
||||||
for n, _ := range shapes {
|
for n := range shapes {
|
||||||
fmt.Println("Shape details: ", shapes[n])
|
fmt.Println("Shape details: ", shapes[n])
|
||||||
fmt.Println("Area of this shape is: ", shapes[n].Area())
|
fmt.Println("Area of this shape is: ", shapes[n].Area())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
Looping through shapes for area ...
|
Looping through shapes for area ...
|
||||||
Shape details: {5 3}
|
Shape details: {5 3}
|
||||||
@@ -40,6 +41,3 @@ Area of this shape is: 15
|
|||||||
Shape details: &{5}
|
Shape details: &{5}
|
||||||
Area of this shape is: 25
|
Area of this shape is: 25
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@@ -6,43 +6,44 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type List []int
|
type List []int
|
||||||
func (l List) Len() int { return len(l) }
|
|
||||||
|
func (l List) Len() int { return len(l) }
|
||||||
func (l *List) Append(val int) { *l = append(*l, val) }
|
func (l *List) Append(val int) { *l = append(*l, val) }
|
||||||
|
|
||||||
type Appender interface {
|
type Appender interface {
|
||||||
Append(int)
|
Append(int)
|
||||||
}
|
}
|
||||||
|
|
||||||
func CountInto(a Appender, start, end int) {
|
func CountInto(a Appender, start, end int) {
|
||||||
for i := start; i <= end; i++ {
|
for i := start; i <= end; i++ {
|
||||||
a.Append(i)
|
a.Append(i)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type Lener interface {
|
type Lener interface {
|
||||||
Len() int
|
Len() int
|
||||||
}
|
}
|
||||||
|
|
||||||
func LongEnough(l Lener) bool {
|
func LongEnough(l Lener) bool {
|
||||||
return l.Len()*10 > 42
|
return l.Len()*10 > 42
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// A bare value
|
// A bare value
|
||||||
var lst List
|
var lst List
|
||||||
// compiler error:
|
// compiler error:
|
||||||
// cannot use lst (type List) as type Appender in function argument:
|
// cannot use lst (type List) as type Appender in function argument:
|
||||||
// List does not implement Appender (Append method requires pointer receiver)
|
// List does not implement Appender (Append method requires pointer receiver)
|
||||||
// CountInto(lst, 1, 10) // INVALID: Append has a pointer receiver
|
// CountInto(lst, 1, 10) // INVALID: Append has a pointer receiver
|
||||||
|
|
||||||
if LongEnough(lst) { // VALID: Identical receiver type
|
if LongEnough(lst) { // VALID: Identical receiver type
|
||||||
fmt.Printf(" - lst is long enough")
|
fmt.Printf(" - lst is long enough")
|
||||||
}
|
}
|
||||||
|
|
||||||
// A pointer value
|
// A pointer value
|
||||||
plst := new(List)
|
plst := new(List)
|
||||||
CountInto(plst, 1, 10) // VALID: Identical receiver type
|
CountInto(plst, 1, 10) // VALID: Identical receiver type
|
||||||
if LongEnough(plst) { // VALID: a *List can be dereferenced for the receiver
|
if LongEnough(plst) { // VALID: a *List can be dereferenced for the receiver
|
||||||
fmt.Printf(" - plst is long enough") // - plst is long enoug
|
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
|
q := &Square{5} // Area() of Square needs a pointer
|
||||||
shapes := []Shaper{r, q}
|
shapes := []Shaper{r, q}
|
||||||
fmt.Println("Looping through shapes for area ...")
|
fmt.Println("Looping through shapes for area ...")
|
||||||
for n, _ := range shapes {
|
for n := range shapes {
|
||||||
fmt.Println("Shape details: ", shapes[n])
|
fmt.Println("Shape details: ", shapes[n])
|
||||||
fmt.Println("Area of this shape is: ", shapes[n].Area())
|
fmt.Println("Area of this shape is: ", shapes[n].Area())
|
||||||
}
|
}
|
||||||
topgen := []TopologicalGenus{r, q}
|
topgen := []TopologicalGenus{r, q}
|
||||||
fmt.Println("Looping through topgen for rank ...")
|
fmt.Println("Looping through topgen for rank ...")
|
||||||
for n, _ := range topgen {
|
for n := range topgen {
|
||||||
fmt.Println("Shape details: ", topgen[n])
|
fmt.Println("Shape details: ", topgen[n])
|
||||||
fmt.Println("Topological Genus of this shape is: ", topgen[n].Rank())
|
fmt.Println("Topological Genus of this shape is: ", topgen[n].Rank())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
Looping through shapes for area ...
|
Looping through shapes for area ...
|
||||||
Shape details: {5 3}
|
Shape details: {5 3}
|
||||||
|
@@ -4,9 +4,9 @@ package main
|
|||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
type Node struct {
|
type Node struct {
|
||||||
le *Node
|
le *Node
|
||||||
data interface{}
|
data interface{}
|
||||||
ri *Node
|
ri *Node
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewNode(left, right *Node) *Node {
|
func NewNode(left, right *Node) *Node {
|
||||||
@@ -18,12 +18,12 @@ func (n *Node) SetData(data interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
root := NewNode(nil,nil)
|
root := NewNode(nil, nil)
|
||||||
root.SetData("root node")
|
root.SetData("root node")
|
||||||
// make child (leaf) nodes:
|
// make child (leaf) nodes:
|
||||||
a := NewNode(nil,nil)
|
a := NewNode(nil, nil)
|
||||||
a.SetData("left node")
|
a.SetData("left node")
|
||||||
b := NewNode(nil,nil)
|
b := NewNode(nil, nil)
|
||||||
b.SetData("right node")
|
b.SetData("right node")
|
||||||
root.le = a
|
root.le = a
|
||||||
root.ri = b
|
root.ri = b
|
||||||
|
@@ -13,7 +13,7 @@ type Stringer interface {
|
|||||||
type Celsius float64
|
type Celsius float64
|
||||||
|
|
||||||
func (c Celsius) String() string {
|
func (c Celsius) String() string {
|
||||||
return strconv.FormatFloat(float64(c),'f', 1, 64) + " °C"
|
return strconv.FormatFloat(float64(c), 'f', 1, 64) + " °C"
|
||||||
}
|
}
|
||||||
|
|
||||||
type Day int
|
type Day int
|
||||||
@@ -26,18 +26,25 @@ func (day Day) String() string {
|
|||||||
|
|
||||||
func print(args ...interface{}) {
|
func print(args ...interface{}) {
|
||||||
for i, arg := range args {
|
for i, arg := range args {
|
||||||
if i > 0 {os.Stdout.WriteString(" ")}
|
if i > 0 {
|
||||||
|
os.Stdout.WriteString(" ")
|
||||||
|
}
|
||||||
switch a := arg.(type) { // type switch
|
switch a := arg.(type) { // type switch
|
||||||
case Stringer: os.Stdout.WriteString(a.String())
|
case Stringer:
|
||||||
case int: os.Stdout.WriteString(strconv.Itoa(a))
|
os.Stdout.WriteString(a.String())
|
||||||
case string: os.Stdout.WriteString(a)
|
case int:
|
||||||
// more types
|
os.Stdout.WriteString(strconv.Itoa(a))
|
||||||
default: os.Stdout.WriteString("???")
|
case string:
|
||||||
|
os.Stdout.WriteString(a)
|
||||||
|
// more types
|
||||||
|
default:
|
||||||
|
os.Stdout.WriteString("???")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
print(Day(1), "was", Celsius(18.36)) // Tuesday was 18.4 °C
|
print(Day(1), "was", Celsius(18.36)) // Tuesday was 18.4 °C
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tuesday was 18.4 °C
|
// Tuesday was 18.4 °C
|
@@ -20,6 +20,7 @@ func main() {
|
|||||||
y := v.Interface().(float64)
|
y := v.Interface().(float64)
|
||||||
fmt.Println(y)
|
fmt.Println(y)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* output:
|
/* output:
|
||||||
type: float64
|
type: float64
|
||||||
value: <float64 Value>
|
value: <float64 Value>
|
||||||
|
@@ -22,6 +22,7 @@ func main() {
|
|||||||
fmt.Println(v.Interface())
|
fmt.Println(v.Interface())
|
||||||
fmt.Println(v)
|
fmt.Println(v)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
settability of v: false
|
settability of v: false
|
||||||
type of v: *float64
|
type of v: *float64
|
||||||
|
@@ -7,7 +7,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type NotknownType struct {
|
type NotknownType struct {
|
||||||
s1, s2, s3 string
|
s1, s2, s3 string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (n NotknownType) String() string {
|
func (n NotknownType) String() string {
|
||||||
@@ -15,19 +15,19 @@ func (n NotknownType) String() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// variable to investigate:
|
// variable to investigate:
|
||||||
var secret interface {} = NotknownType{"Ada", "Go", "Oberon"}
|
var secret interface{} = NotknownType{"Ada", "Go", "Oberon"}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
value := reflect.ValueOf(secret) // <main.NotknownType Value>
|
value := reflect.ValueOf(secret) // <main.NotknownType Value>
|
||||||
typ := reflect.TypeOf(secret) // main.NotknownType
|
typ := reflect.TypeOf(secret) // main.NotknownType
|
||||||
// alternative:
|
// alternative:
|
||||||
//typ := value.Type() // main.NotknownType
|
//typ := value.Type() // main.NotknownType
|
||||||
fmt.Println(typ)
|
fmt.Println(typ)
|
||||||
knd := value.Kind() // struct
|
knd := value.Kind() // struct
|
||||||
fmt.Println(knd)
|
fmt.Println(knd)
|
||||||
|
|
||||||
// iterate through the fields of the struct:
|
// iterate through the fields of the struct:
|
||||||
for i:= 0; i < value.NumField(); i++ {
|
for i := 0; i < value.NumField(); i++ {
|
||||||
fmt.Printf("Field %d: %v\n", i, value.Field(i))
|
fmt.Printf("Field %d: %v\n", i, value.Field(i))
|
||||||
// error: panic: reflect.Value.SetString using value obtained using unexported field
|
// error: panic: reflect.Value.SetString using value obtained using unexported field
|
||||||
//value.Field(i).SetString("C#")
|
//value.Field(i).SetString("C#")
|
||||||
@@ -35,8 +35,9 @@ func main() {
|
|||||||
|
|
||||||
// call the first method, which is String():
|
// call the first method, which is String():
|
||||||
results := value.Method(0).Call(nil)
|
results := value.Method(0).Call(nil)
|
||||||
fmt.Println(results) // [Ada - Go - Oberon]
|
fmt.Println(results) // [Ada - Go - Oberon]
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
main.NotknownType
|
main.NotknownType
|
||||||
struct
|
struct
|
||||||
|
@@ -24,6 +24,7 @@ func main() {
|
|||||||
s.Field(1).SetString("Sunset Strip")
|
s.Field(1).SetString("Sunset Strip")
|
||||||
fmt.Println("t is now", t)
|
fmt.Println("t is now", t)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
0: A int = 23
|
0: A int = 23
|
||||||
1: B string = skidoo
|
1: B string = skidoo
|
||||||
|
@@ -39,11 +39,13 @@ func (p IntArray) Less(i, j int) bool { return p[i] < p[j] }
|
|||||||
func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
|
func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
|
||||||
|
|
||||||
type Float64Array []float64
|
type Float64Array []float64
|
||||||
|
|
||||||
func (p Float64Array) Len() int { return len(p) }
|
func (p Float64Array) Len() int { return len(p) }
|
||||||
func (p Float64Array) Less(i, j int) bool { return p[i] < p[j] }
|
func (p Float64Array) Less(i, j int) bool { return p[i] < p[j] }
|
||||||
func (p Float64Array) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
|
func (p Float64Array) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
|
||||||
|
|
||||||
type StringArray []string
|
type StringArray []string
|
||||||
|
|
||||||
func (p StringArray) Len() int { return len(p) }
|
func (p StringArray) Len() int { return len(p) }
|
||||||
func (p StringArray) Less(i, j int) bool { return p[i] < p[j] }
|
func (p StringArray) Less(i, j int) bool { return p[i] < p[j] }
|
||||||
func (p StringArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
|
func (p StringArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
|
||||||
|
@@ -6,73 +6,72 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"./sort"
|
||||||
"./sort"
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
// sorting of slice of integers
|
// sorting of slice of integers
|
||||||
func ints() {
|
func ints() {
|
||||||
data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586}
|
data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586}
|
||||||
a := sort.IntArray(data) //conversion to type IntArray
|
a := sort.IntArray(data) //conversion to type IntArray
|
||||||
sort.Sort(a)
|
sort.Sort(a)
|
||||||
if !sort.IsSorted(a) {
|
if !sort.IsSorted(a) {
|
||||||
panic("fail")
|
panic("fail")
|
||||||
}
|
}
|
||||||
fmt.Printf("The sorted array is: %v\n", a)
|
fmt.Printf("The sorted array is: %v\n", a)
|
||||||
}
|
}
|
||||||
|
|
||||||
// sorting of slice of strings
|
// sorting of slice of strings
|
||||||
func strings() {
|
func strings() {
|
||||||
data := []string{"monday", "friday", "tuesday", "wednesday", "sunday","thursday", "", "saturday"}
|
data := []string{"monday", "friday", "tuesday", "wednesday", "sunday", "thursday", "", "saturday"}
|
||||||
a := sort.StringArray(data)
|
a := sort.StringArray(data)
|
||||||
sort.Sort(a)
|
sort.Sort(a)
|
||||||
if !sort.IsSorted(a) {
|
if !sort.IsSorted(a) {
|
||||||
panic("fail")
|
panic("fail")
|
||||||
}
|
}
|
||||||
fmt.Printf("The sorted array is: %v\n", a)
|
fmt.Printf("The sorted array is: %v\n", a)
|
||||||
}
|
}
|
||||||
|
|
||||||
// a type which describes a day of the week
|
// a type which describes a day of the week
|
||||||
type day struct {
|
type day struct {
|
||||||
num int
|
num int
|
||||||
shortName string
|
shortName string
|
||||||
longName string
|
longName string
|
||||||
}
|
}
|
||||||
|
|
||||||
type dayArray struct {
|
type dayArray struct {
|
||||||
data []*day
|
data []*day
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *dayArray) Len() int { return len(p.data) }
|
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) 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) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i] }
|
||||||
|
|
||||||
// sorting of custom type day
|
// sorting of custom type day
|
||||||
func days() {
|
func days() {
|
||||||
Sunday := day{0, "SUN", "Sunday"}
|
Sunday := day{0, "SUN", "Sunday"}
|
||||||
Monday := day{1, "MON", "Monday"}
|
Monday := day{1, "MON", "Monday"}
|
||||||
Tuesday := day{2, "TUE", "Tuesday"}
|
Tuesday := day{2, "TUE", "Tuesday"}
|
||||||
Wednesday := day{3, "WED", "Wednesday"}
|
Wednesday := day{3, "WED", "Wednesday"}
|
||||||
Thursday := day{4, "THU", "Thursday"}
|
Thursday := day{4, "THU", "Thursday"}
|
||||||
Friday := day{5, "FRI", "Friday"}
|
Friday := day{5, "FRI", "Friday"}
|
||||||
Saturday := day{6, "SAT", "Saturday"}
|
Saturday := day{6, "SAT", "Saturday"}
|
||||||
data := []*day{&Tuesday, &Thursday, &Wednesday, &Sunday, &Monday, &Friday, &Saturday}
|
data := []*day{&Tuesday, &Thursday, &Wednesday, &Sunday, &Monday, &Friday, &Saturday}
|
||||||
a := dayArray{data}
|
a := dayArray{data}
|
||||||
sort.Sort(&a)
|
sort.Sort(&a)
|
||||||
if !sort.IsSorted(&a) {
|
if !sort.IsSorted(&a) {
|
||||||
panic("fail")
|
panic("fail")
|
||||||
}
|
}
|
||||||
for _, d := range data {
|
for _, d := range data {
|
||||||
fmt.Printf("%s ", d.longName)
|
fmt.Printf("%s ", d.longName)
|
||||||
}
|
}
|
||||||
fmt.Printf("\n")
|
fmt.Printf("\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
ints()
|
ints()
|
||||||
strings()
|
strings()
|
||||||
days()
|
days()
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
|
@@ -2,11 +2,11 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"bufio"
|
"bufio"
|
||||||
"bytes"
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
var r io.Reader
|
var r io.Reader
|
||||||
|
@@ -43,8 +43,8 @@ package cgl
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"fmt"
|
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
@@ -34,22 +34,22 @@ func main() {
|
|||||||
}
|
}
|
||||||
// testing with switch:
|
// testing with switch:
|
||||||
switch t := areaIntf.(type) {
|
switch t := areaIntf.(type) {
|
||||||
case *Square:
|
case *Square:
|
||||||
fmt.Printf("Type Square %T with value %v\n", t, t)
|
fmt.Printf("Type Square %T with value %v\n", t, t)
|
||||||
case *Circle:
|
case *Circle:
|
||||||
fmt.Printf("Type Circle %T with value %v\n", t, t)
|
fmt.Printf("Type Circle %T with value %v\n", t, t)
|
||||||
/*
|
/*
|
||||||
case bool:
|
case bool:
|
||||||
fmt.Printf("Type boolean %t\n", t)
|
fmt.Printf("Type boolean %t\n", t)
|
||||||
case int:
|
case int:
|
||||||
fmt.Printf("Type int %d\n", t)
|
fmt.Printf("Type int %d\n", t)
|
||||||
case *bool:
|
case *bool:
|
||||||
fmt.Printf("Type pointer to boolean %t\n", *t)
|
fmt.Printf("Type pointer to boolean %t\n", *t)
|
||||||
case *int:
|
case *int:
|
||||||
fmt.Printf("Type pointer to int %d\n", *t)
|
fmt.Printf("Type pointer to int %d\n", *t)
|
||||||
*/
|
*/
|
||||||
default:
|
default:
|
||||||
fmt.Printf("Unexpected type %T", t)
|
fmt.Printf("Unexpected type %T", t)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -1,11 +1,11 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
|
||||||
"io"
|
|
||||||
"fmt"
|
|
||||||
"bufio"
|
"bufio"
|
||||||
"flag"
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
func cat(r *bufio.Reader) {
|
func cat(r *bufio.Reader) {
|
||||||
@@ -33,4 +33,3 @@ func main() {
|
|||||||
cat(bufio.NewReader(f))
|
cat(bufio.NewReader(f))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -1,8 +1,8 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
|
||||||
"flag" // command line option parser
|
"flag" // command line option parser
|
||||||
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
var NewLine = flag.Bool("n", false, "print newline") // echo -n flag, of type *bool
|
var NewLine = flag.Bool("n", false, "print newline") // echo -n flag, of type *bool
|
||||||
@@ -19,7 +19,7 @@ func main() {
|
|||||||
for i := 0; i < flag.NArg(); i++ {
|
for i := 0; i < flag.NArg(); i++ {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
s += " "
|
s += " "
|
||||||
if *NewLine { // -n is parsed, flag becomes true
|
if *NewLine { // -n is parsed, flag becomes true
|
||||||
s += Newline
|
s += Newline
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -16,8 +16,8 @@ func main() {
|
|||||||
inputFile, inputError := os.Open("input.dat")
|
inputFile, inputError := os.Open("input.dat")
|
||||||
if inputError != nil {
|
if inputError != nil {
|
||||||
fmt.Printf("An error occurred on opening the inputfile\n" +
|
fmt.Printf("An error occurred on opening the inputfile\n" +
|
||||||
"Does the file exist?\n" +
|
"Does the file exist?\n" +
|
||||||
"Have you got acces to it?\n")
|
"Have you got acces to it?\n")
|
||||||
return // exit the function on error
|
return // exit the function on error
|
||||||
}
|
}
|
||||||
defer inputFile.Close()
|
defer inputFile.Close()
|
||||||
|
@@ -1,12 +1,12 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
|
||||||
"bufio"
|
"bufio"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main () {
|
func main() {
|
||||||
// var outputWriter *bufio.Writer
|
// var outputWriter *bufio.Writer
|
||||||
// var outputFile *os.File
|
// var outputFile *os.File
|
||||||
// var outputError os.Error
|
// var outputError os.Error
|
||||||
@@ -21,7 +21,7 @@ func main () {
|
|||||||
outputWriter := bufio.NewWriter(outputFile)
|
outputWriter := bufio.NewWriter(outputFile)
|
||||||
outputString := "hello world!\n"
|
outputString := "hello world!\n"
|
||||||
|
|
||||||
for i:=0; i<10; i++ {
|
for i := 0; i < 10; i++ {
|
||||||
outputWriter.WriteString(outputString)
|
outputWriter.WriteString(outputString)
|
||||||
}
|
}
|
||||||
outputWriter.Flush()
|
outputWriter.Flush()
|
||||||
|
@@ -3,8 +3,8 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"fmt"
|
|
||||||
"encoding/gob"
|
"encoding/gob"
|
||||||
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -22,9 +22,9 @@ func main() {
|
|||||||
// Initialize the encoder and decoder. Normally enc and dec would be
|
// Initialize the encoder and decoder. Normally enc and dec would be
|
||||||
// bound to network connections and the encoder and decoder would
|
// bound to network connections and the encoder and decoder would
|
||||||
// run in different processes.
|
// 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.
|
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.
|
// Encode (send) the value.
|
||||||
err := enc.Encode(P{3, 4, 5, "Pythagoras"})
|
err := enc.Encode(P{3, 4, 5, "Pythagoras"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -38,4 +38,5 @@ func main() {
|
|||||||
}
|
}
|
||||||
fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y)
|
fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Output: "Pythagoras": {3,4}
|
// Output: "Pythagoras": {3,4}
|
||||||
|
@@ -8,24 +8,24 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Address struct {
|
type Address struct {
|
||||||
Type string
|
Type string
|
||||||
City string
|
City string
|
||||||
Country string
|
Country string
|
||||||
}
|
}
|
||||||
|
|
||||||
type VCard struct {
|
type VCard struct {
|
||||||
FirstName string
|
FirstName string
|
||||||
LastName string
|
LastName string
|
||||||
Addresses []*Address
|
Addresses []*Address
|
||||||
Remark string
|
Remark string
|
||||||
}
|
}
|
||||||
|
|
||||||
var content string
|
var content string
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
pa := &Address{"private", "Aartselaar","Belgium"}
|
pa := &Address{"private", "Aartselaar", "Belgium"}
|
||||||
wa := &Address{"work", "Boom", "Belgium"}
|
wa := &Address{"work", "Boom", "Belgium"}
|
||||||
vc := VCard{"Jan", "Kersschot", []*Address{pa,wa}, "none"}
|
vc := VCard{"Jan", "Kersschot", []*Address{pa, wa}, "none"}
|
||||||
// fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none}:
|
// fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none}:
|
||||||
// using an encoder:
|
// using an encoder:
|
||||||
file, _ := os.OpenFile("vcard.gob", os.O_CREATE|os.O_WRONLY, 0666)
|
file, _ := os.OpenFile("vcard.gob", os.O_CREATE|os.O_WRONLY, 0666)
|
||||||
@@ -36,4 +36,3 @@ func main() {
|
|||||||
log.Println("Error in encoding gob")
|
log.Println("Error in encoding gob")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -2,10 +2,10 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"bufio"
|
"bufio"
|
||||||
"os"
|
|
||||||
"compress/gzip"
|
"compress/gzip"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
@@ -2,8 +2,8 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"crypto/sha1"
|
"crypto/sha1"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
)
|
)
|
||||||
@@ -18,12 +18,13 @@ func main() {
|
|||||||
hasher.Reset()
|
hasher.Reset()
|
||||||
data := []byte("We shall overcome!")
|
data := []byte("We shall overcome!")
|
||||||
n, err := hasher.Write(data)
|
n, err := hasher.Write(data)
|
||||||
if n!=len(data) || err!=nil {
|
if n != len(data) || err != nil {
|
||||||
log.Printf("Hash write error: %v / %v", n, err)
|
log.Printf("Hash write error: %v / %v", n, err)
|
||||||
}
|
}
|
||||||
checksum := hasher.Sum(b)
|
checksum := hasher.Sum(b)
|
||||||
fmt.Printf("Result: %x\n", checksum)
|
fmt.Printf("Result: %x\n", checksum)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
Result: a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
|
Result: a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
|
||||||
Result: [169 74 143 229 204 177 155 166 28 76 8 115 211 145 233 135 152 47 187 211]
|
Result: [169 74 143 229 204 177 155 166 28 76 8 115 211 145 233 135 152 47 187 211]
|
||||||
|
@@ -2,29 +2,29 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Address struct {
|
type Address struct {
|
||||||
Type string
|
Type string
|
||||||
City string
|
City string
|
||||||
Country string
|
Country string
|
||||||
}
|
}
|
||||||
|
|
||||||
type VCard struct {
|
type VCard struct {
|
||||||
FirstName string
|
FirstName string
|
||||||
LastName string
|
LastName string
|
||||||
Addresses []*Address
|
Addresses []*Address
|
||||||
Remark string
|
Remark string
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
pa := &Address{"private", "Aartselaar","Belgium"}
|
pa := &Address{"private", "Aartselaar", "Belgium"}
|
||||||
wa := &Address{"work", "Boom", "Belgium"}
|
wa := &Address{"work", "Boom", "Belgium"}
|
||||||
vc := VCard{"Jan", "Kersschot", []*Address{pa,wa}, "none"}
|
vc := VCard{"Jan", "Kersschot", []*Address{pa, wa}, "none"}
|
||||||
// fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none}:
|
// fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none}:
|
||||||
// JSON format:
|
// JSON format:
|
||||||
js, _ := json.Marshal(vc)
|
js, _ := json.Marshal(vc)
|
||||||
|
@@ -32,6 +32,7 @@ func main() {
|
|||||||
fmt.Printf("From XML: %#v\n", tx)
|
fmt.Printf("From XML: %#v\n", tx)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output with
|
/* Output with
|
||||||
type thing struct {
|
type thing struct {
|
||||||
Field1 int
|
Field1 int
|
||||||
|
@@ -4,8 +4,8 @@ package main
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
// "io/ioutil"
|
// "io/ioutil"
|
||||||
// "strings"
|
// "strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -31,6 +31,7 @@ func main() {
|
|||||||
fmt.Println(col2)
|
fmt.Println(col2)
|
||||||
fmt.Println(col3)
|
fmt.Println(col3)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
[ABC FUNC GO]
|
[ABC FUNC GO]
|
||||||
[40 56 45]
|
[40 56 45]
|
||||||
|
@@ -21,10 +21,8 @@ func main() {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
r := bufio.NewReader(fin)
|
r := bufio.NewReader(fin)
|
||||||
for line, _, err := r.ReadLine();
|
for line, _, err := r.ReadLine(); err != io.EOF; line, _, err = r.ReadLine() {
|
||||||
err != io.EOF;
|
fmt.Printf("Lines: %v (error %v)\n", string(line), err)
|
||||||
line, _, err = r.ReadLine() {
|
|
||||||
fmt.Printf("Lines: %v (error %v)\n", string(line), err)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -7,10 +7,10 @@ import (
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
firstName, lastName, s string
|
firstName, lastName, s string
|
||||||
i int
|
i int
|
||||||
f float32
|
f float32
|
||||||
input = "56.12 / 5212 / Go"
|
input = "56.12 / 5212 / Go"
|
||||||
format = "%f / %d / %s"
|
format = "%f / %d / %s"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
@@ -2,17 +2,17 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"bufio"
|
"bufio"
|
||||||
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
var inputReader *bufio.Reader
|
var inputReader *bufio.Reader
|
||||||
var input string
|
var input string
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
inputReader = bufio.NewReader(os.Stdin) // reader for input
|
inputReader = bufio.NewReader(os.Stdin) // reader for input
|
||||||
fmt.Println("Please enter some input: ")
|
fmt.Println("Please enter some input: ")
|
||||||
input, err = inputReader.ReadString('\n')
|
input, err = inputReader.ReadString('\n')
|
||||||
|
|
||||||
|
@@ -1,41 +1,51 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bufio"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"bufio"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
inputReader := bufio.NewReader(os.Stdin)
|
inputReader := bufio.NewReader(os.Stdin)
|
||||||
fmt.Println("Please enter your name:")
|
fmt.Println("Please enter your name:")
|
||||||
input, err := inputReader.ReadString('\n')
|
input, err := inputReader.ReadString('\n')
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("There were errors reading, exiting program.")
|
fmt.Println("There were errors reading, exiting program.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Printf("Your name is %s", input)
|
fmt.Printf("Your name is %s", input)
|
||||||
// For Unix: test with delimiter "\n", for Windows: test with "\r\n"
|
// For Unix: test with delimiter "\n", for Windows: test with "\r\n"
|
||||||
switch input {
|
switch input {
|
||||||
case "Philip\r\n": fmt.Println("Welcome Philip!")
|
case "Philip\r\n":
|
||||||
case "Chris\r\n": fmt.Println("Welcome Chris!")
|
fmt.Println("Welcome Philip!")
|
||||||
case "Ivo\r\n": fmt.Println("Welcome Ivo!")
|
case "Chris\r\n":
|
||||||
default: fmt.Printf("You are not welcome here! Goodbye!")
|
fmt.Println("Welcome Chris!")
|
||||||
}
|
case "Ivo\r\n":
|
||||||
|
fmt.Println("Welcome Ivo!")
|
||||||
|
default:
|
||||||
|
fmt.Printf("You are not welcome here! Goodbye!")
|
||||||
|
}
|
||||||
|
|
||||||
// version 2:
|
// version 2:
|
||||||
switch input {
|
switch input {
|
||||||
case "Philip\r\n": fallthrough
|
case "Philip\r\n":
|
||||||
case "Ivo\r\n": fallthrough
|
fallthrough
|
||||||
case "Chris\r\n": fmt.Printf("Welcome %s\n", input)
|
case "Ivo\r\n":
|
||||||
default: fmt.Printf("You are not welcome here! Goodbye!\n")
|
fallthrough
|
||||||
}
|
case "Chris\r\n":
|
||||||
|
fmt.Printf("Welcome %s\n", input)
|
||||||
|
default:
|
||||||
|
fmt.Printf("You are not welcome here! Goodbye!\n")
|
||||||
|
}
|
||||||
|
|
||||||
// version 3:
|
// version 3:
|
||||||
switch input {
|
switch input {
|
||||||
case "Philip\r\n", "Ivo\r\n": fmt.Printf("Welcome %s\n", input)
|
case "Philip\r\n", "Ivo\r\n":
|
||||||
default: fmt.Printf("You are not welcome here! Goodbye!\n")
|
fmt.Printf("Welcome %s\n", input)
|
||||||
}
|
default:
|
||||||
|
fmt.Printf("You are not welcome here! Goodbye!\n")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -2,13 +2,13 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/xml"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"encoding/xml"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var t, token xml.Token
|
var t, token xml.Token
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
input := "<Person><FirstName>Laura</FirstName><LastName>Lynn</LastName></Person>"
|
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() {
|
for t, err = p.Token(); err == nil; t, err = p.Token() {
|
||||||
switch token := t.(type) {
|
switch token := t.(type) {
|
||||||
case xml.StartElement:
|
case xml.StartElement:
|
||||||
name := token.Name.Local
|
name := token.Name.Local
|
||||||
fmt.Printf("Token name: %s\n", name)
|
fmt.Printf("Token name: %s\n", name)
|
||||||
for _, attr := range token.Attr {
|
for _, attr := range token.Attr {
|
||||||
attrName := attr.Name.Local
|
attrName := attr.Name.Local
|
||||||
attrValue := attr.Value
|
attrValue := attr.Value
|
||||||
fmt.Printf("An attribute is: %s %s\n", attrName, attrValue)
|
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.EndElement:
|
||||||
|
fmt.Println("End of token")
|
||||||
|
case xml.CharData:
|
||||||
|
content := string([]byte(token))
|
||||||
|
fmt.Printf("This is the content: %v\n", content)
|
||||||
|
// ...
|
||||||
|
default:
|
||||||
|
// ...
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
Token name: Person
|
Token name: Person
|
||||||
Token name: FirstName
|
Token name: FirstName
|
||||||
|
@@ -11,4 +11,5 @@ var errNotFound error = errors.New("Not found error")
|
|||||||
func main() {
|
func main() {
|
||||||
fmt.Printf("error: %v", errNotFound)
|
fmt.Printf("error: %v", errNotFound)
|
||||||
}
|
}
|
||||||
|
|
||||||
// error: Not found error
|
// error: Not found error
|
@@ -1,10 +1,10 @@
|
|||||||
// even.go
|
// even.go
|
||||||
package even
|
package even
|
||||||
|
|
||||||
func Even(i int) bool { // Exported function
|
func Even(i int) bool { // Exported function
|
||||||
return i%2 == 0
|
return i%2 == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func Odd(i int) bool { // Exported function
|
func Odd(i int) bool { // Exported function
|
||||||
return i%2 != 0
|
return i%2 != 0
|
||||||
}
|
}
|
||||||
|
@@ -2,12 +2,12 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"even/even"
|
"even/even"
|
||||||
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
for i:=0; i<=100; i++ {
|
for i := 0; i <= 100; i++ {
|
||||||
fmt.Printf("Is the integer %d even? %v\n", i, even.Even(i))
|
fmt.Printf("Is the integer %d even? %v\n", i, even.Even(i))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,61 +1,61 @@
|
|||||||
// exec.go
|
// exec.go
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"os/exec"
|
|
||||||
"os"
|
"os"
|
||||||
|
"os/exec"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// 1) os.StartProcess //
|
// 1) os.StartProcess //
|
||||||
/*********************/
|
/*********************/
|
||||||
/* Linux: */
|
/* Linux: */
|
||||||
env := os.Environ()
|
env := os.Environ()
|
||||||
procAttr := &os.ProcAttr{
|
procAttr := &os.ProcAttr{
|
||||||
Env: env,
|
Env: env,
|
||||||
Files: []*os.File{
|
Files: []*os.File{
|
||||||
os.Stdin,
|
os.Stdin,
|
||||||
os.Stdout,
|
os.Stdout,
|
||||||
os.Stderr,
|
os.Stderr,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
// 1st example: list files
|
// 1st example: list files
|
||||||
pid, err := os.StartProcess("/bin/ls", []string{"ls", "-l"}, procAttr)
|
pid, err := os.StartProcess("/bin/ls", []string{"ls", "-l"}, procAttr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error %v starting process!", err) //
|
fmt.Printf("Error %v starting process!", err) //
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
fmt.Printf("The process id is %v", pid)
|
fmt.Printf("The process id is %v", pid)
|
||||||
// 2nd example: show all processes
|
// 2nd example: show all processes
|
||||||
pid, err = os.StartProcess("/bin/ps", []string{"-e", "-opid,ppid,comm"}, procAttr)
|
pid, err = os.StartProcess("/bin/ps", []string{"-e", "-opid,ppid,comm"}, procAttr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error %v starting process!", err) //
|
fmt.Printf("Error %v starting process!", err) //
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
fmt.Printf("The process id is %v", pid)
|
fmt.Printf("The process id is %v", pid)
|
||||||
/* Output 1st:
|
/* Output 1st:
|
||||||
The process id is &{2054 0}total 2056
|
The process id is &{2054 0}total 2056
|
||||||
-rwxr-xr-x 1 ivo ivo 1157555 2011-07-04 16:48 Mieken_exec
|
-rwxr-xr-x 1 ivo ivo 1157555 2011-07-04 16:48 Mieken_exec
|
||||||
-rw-r--r-- 1 ivo ivo 2124 2011-07-04 16:48 Mieken_exec.go
|
-rw-r--r-- 1 ivo ivo 2124 2011-07-04 16:48 Mieken_exec.go
|
||||||
-rw-r--r-- 1 ivo ivo 18528 2011-07-04 16:48 Mieken_exec_go_.6
|
-rw-r--r-- 1 ivo ivo 18528 2011-07-04 16:48 Mieken_exec_go_.6
|
||||||
-rwxr-xr-x 1 ivo ivo 913920 2011-06-03 16:13 panic.exe
|
-rwxr-xr-x 1 ivo ivo 913920 2011-06-03 16:13 panic.exe
|
||||||
-rw-r--r-- 1 ivo ivo 180 2011-04-11 20:39 panic.go
|
-rw-r--r-- 1 ivo ivo 180 2011-04-11 20:39 panic.go
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// 2) exec.Run //
|
// 2) exec.Run //
|
||||||
/***************/
|
/***************/
|
||||||
// Linux: OK, but not for ls ?
|
// Linux: OK, but not for ls ?
|
||||||
// cmd := exec.Command("ls", "-l") // no error, but doesn't show anything ?
|
// cmd := exec.Command("ls", "-l") // no error, but doesn't show anything ?
|
||||||
// cmd := exec.Command("ls") // no error, but doesn't show anything ?
|
// cmd := exec.Command("ls") // no error, but doesn't show anything ?
|
||||||
cmd := exec.Command("gedit") // this opens a gedit-window
|
cmd := exec.Command("gedit") // this opens a gedit-window
|
||||||
err = cmd.Run()
|
err = cmd.Run()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error %v executing command!", err)
|
fmt.Printf("Error %v executing command!", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
fmt.Printf("The command is %v", cmd)
|
fmt.Printf("The command is %v", cmd)
|
||||||
// The command is &{/bin/ls [ls -l] [] <nil> <nil> <nil> 0xf840000210 <nil> true [0xf84000ea50 0xf84000e9f0 0xf84000e9c0] [0xf84000ea50 0xf84000e9f0 0xf84000e9c0] [] [] 0xf8400128c0}
|
// The command is &{/bin/ls [ls -l] [] <nil> <nil> <nil> 0xf840000210 <nil> true [0xf84000ea50 0xf84000e9f0 0xf84000e9c0] [0xf84000ea50 0xf84000e9f0 0xf84000e9c0] [] [] 0xf8400128c0}
|
||||||
}
|
}
|
||||||
|
|
||||||
// in Windows: uitvoering: Error fork/exec /bin/ls: The system cannot find the path specified. starting process!
|
// in Windows: uitvoering: Error fork/exec /bin/ls: The system cannot find the path specified. starting process!
|
||||||
|
|
||||||
|
|
||||||
|
@@ -2,29 +2,30 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"./parse/parse"
|
"./parse/parse"
|
||||||
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var examples = []string{
|
var examples = []string{
|
||||||
"1 2 3 4 5",
|
"1 2 3 4 5",
|
||||||
"100 50 25 12.5 6.25",
|
"100 50 25 12.5 6.25",
|
||||||
"2 + 2 = 4",
|
"2 + 2 = 4",
|
||||||
"1st class",
|
"1st class",
|
||||||
"",
|
"",
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, ex := range examples {
|
for _, ex := range examples {
|
||||||
fmt.Printf("Parsing %q:\n ", ex)
|
fmt.Printf("Parsing %q:\n ", ex)
|
||||||
nums, err := parse.Parse(ex)
|
nums, err := parse.Parse(ex)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err) // here String() method from ParseError is used
|
fmt.Println(err) // here String() method from ParseError is used
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
fmt.Println(nums)
|
fmt.Println(nums)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
Parsing "1 2 3 4 5":
|
Parsing "1 2 3 4 5":
|
||||||
[1 2 3 4 5]
|
[1 2 3 4 5]
|
||||||
|
@@ -3,49 +3,49 @@ package parse
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// A ParseError indicates an error in converting a word into an integer.
|
// A ParseError indicates an error in converting a word into an integer.
|
||||||
type ParseError struct {
|
type ParseError struct {
|
||||||
Index int // The index into the space-separated list of words.
|
Index int // The index into the space-separated list of words.
|
||||||
Word string // The word that generated the parse error.
|
Word string // The word that generated the parse error.
|
||||||
Err error // The raw error that precipitated this error, if any.
|
Err error // The raw error that precipitated this error, if any.
|
||||||
}
|
}
|
||||||
|
|
||||||
// String returns a human-readable error message.
|
// String returns a human-readable error message.
|
||||||
func (e *ParseError) String() string {
|
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.
|
// Parse parses the space-separated words in in put as integers.
|
||||||
func Parse(input string) (numbers []int, err error) {
|
func Parse(input string) (numbers []int, err error) {
|
||||||
defer func() {
|
defer func() {
|
||||||
if r := recover(); r != nil {
|
if r := recover(); r != nil {
|
||||||
var ok bool
|
var ok bool
|
||||||
err, ok = r.(error)
|
err, ok = r.(error)
|
||||||
if !ok {
|
if !ok {
|
||||||
err = fmt.Errorf("pkg: %v", r)
|
err = fmt.Errorf("pkg: %v", r)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
fields := strings.Fields(input)
|
fields := strings.Fields(input)
|
||||||
numbers = fields2numbers(fields)
|
numbers = fields2numbers(fields)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func fields2numbers(fields []string) (numbers []int) {
|
func fields2numbers(fields []string) (numbers []int) {
|
||||||
if len(fields) == 0 {
|
if len(fields) == 0 {
|
||||||
panic("no words to parse")
|
panic("no words to parse")
|
||||||
}
|
}
|
||||||
for idx, field := range fields {
|
for idx, field := range fields {
|
||||||
num, err := strconv.Atoi(field)
|
num, err := strconv.Atoi(field)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(&ParseError{idx, field, err})
|
panic(&ParseError{idx, field, err})
|
||||||
}
|
}
|
||||||
numbers = append(numbers, num)
|
numbers = append(numbers, num)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@@ -7,7 +7,7 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
fmt.Println(" sync", testing.Benchmark(BenchmarkChannelSync).String())
|
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) {
|
func BenchmarkChannelSync(b *testing.B) {
|
||||||
@@ -18,7 +18,7 @@ func BenchmarkChannelSync(b *testing.B) {
|
|||||||
}
|
}
|
||||||
close(ch)
|
close(ch)
|
||||||
}()
|
}()
|
||||||
for _ = range ch {
|
for range ch {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,6 +30,6 @@ func BenchmarkChannelBuffered(b *testing.B) {
|
|||||||
}
|
}
|
||||||
close(ch)
|
close(ch)
|
||||||
}()
|
}()
|
||||||
for _ = range ch {
|
for range ch {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -7,7 +7,7 @@ import (
|
|||||||
|
|
||||||
var ngoroutine = flag.Int("n", 100000, "how many goroutines")
|
var ngoroutine = flag.Int("n", 100000, "how many goroutines")
|
||||||
|
|
||||||
func f(left, right chan int) { left <- 1+<-right }
|
func f(left, right chan int) { left <- 1 + <-right }
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
@@ -13,4 +13,3 @@ func pump(ch chan int) {
|
|||||||
ch <- i
|
ch <- i
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -47,6 +47,7 @@ func main() {
|
|||||||
fmt.Println("Salary changed:")
|
fmt.Println("Salary changed:")
|
||||||
fmt.Println(bs)
|
fmt.Println(bs)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
Person - name is: Smith Bill - salary is: 2500.50
|
Person - name is: Smith Bill - salary is: 2500.50
|
||||||
Salary changed:
|
Salary changed:
|
||||||
|
@@ -43,6 +43,7 @@ func BuildLazyIntEvaluator(evalFunc EvalFunc, initState Any) func() int {
|
|||||||
return ef().(int)
|
return ef().(int)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
0th even: 0
|
0th even: 0
|
||||||
1th even: 2
|
1th even: 2
|
||||||
|
@@ -30,4 +30,5 @@ func getData(ch chan string) {
|
|||||||
fmt.Printf("%s ", input)
|
fmt.Printf("%s ", input)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Washington Tripoli London Beijing Tokio
|
// Washington Tripoli London Beijing Tokio
|
@@ -26,4 +26,5 @@ func getData(ch chan string) {
|
|||||||
fmt.Printf("%s ", input)
|
fmt.Printf("%s ", input)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Washington Tripoli London Beijing Tokio
|
// Washington Tripoli London Beijing Tokio
|
@@ -2,8 +2,8 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -24,26 +24,24 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func pump1(ch chan int) {
|
func pump1(ch chan int) {
|
||||||
for i:=0; ; i++ {
|
for i := 0; ; i++ {
|
||||||
ch <- i*2
|
ch <- i * 2
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func pump2(ch chan int) {
|
func pump2(ch chan int) {
|
||||||
for i:=0; ; i++ {
|
for i := 0; ; i++ {
|
||||||
ch <- i+5
|
ch <- i + 5
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func suck(ch1,ch2 chan int) {
|
func suck(ch1, ch2 chan int) {
|
||||||
for i := 0; ; i++ {
|
for i := 0; ; i++ {
|
||||||
select {
|
select {
|
||||||
case v := <- ch1:
|
case v := <-ch1:
|
||||||
fmt.Printf("%d - Received on channel 1: %d\n", i, v)
|
fmt.Printf("%d - Received on channel 1: %d\n", i, v)
|
||||||
case v := <- ch2:
|
case v := <-ch2:
|
||||||
fmt.Printf("%d - Received on channel 2: %d\n", i, v)
|
fmt.Printf("%d - Received on channel 2: %d\n", i, v)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@@ -8,19 +8,19 @@ import (
|
|||||||
var resume chan int
|
var resume chan int
|
||||||
|
|
||||||
func integers() chan int {
|
func integers() chan int {
|
||||||
yield := make (chan int)
|
yield := make(chan int)
|
||||||
count := 0
|
count := 0
|
||||||
go func () {
|
go func() {
|
||||||
for {
|
for {
|
||||||
yield <- count
|
yield <- count
|
||||||
count++
|
count++
|
||||||
}
|
}
|
||||||
} ()
|
}()
|
||||||
return yield
|
return yield
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateInteger() int {
|
func generateInteger() int {
|
||||||
return <-resume
|
return <-resume
|
||||||
}
|
}
|
||||||
func main() {
|
func main() {
|
||||||
resume = integers()
|
resume = integers()
|
||||||
|
@@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
const MAXREQS = 50
|
const MAXREQS = 50
|
||||||
|
|
||||||
var sem = make(chan int, MAXREQS)
|
var sem = make(chan int, MAXREQS)
|
||||||
|
|
||||||
type Request struct {
|
type Request struct {
|
||||||
@@ -13,16 +14,16 @@ func process(r *Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func handle(r *Request) {
|
func handle(r *Request) {
|
||||||
sem <- 1 // doesn't matter what we put in it
|
sem <- 1 // doesn't matter what we put in it
|
||||||
process(r)
|
process(r)
|
||||||
<-sem // one empty place in the buffer: the next request can start
|
<-sem // one empty place in the buffer: the next request can start
|
||||||
}
|
}
|
||||||
|
|
||||||
func server(service chan *Request) {
|
func server(service chan *Request) {
|
||||||
for {
|
for {
|
||||||
request := <-service
|
request := <-service
|
||||||
go handle(request)
|
go handle(request)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
@@ -19,10 +19,10 @@ func run(op binOp, req *Request) {
|
|||||||
func server(op binOp, service chan *Request, quit chan bool) {
|
func server(op binOp, service chan *Request, quit chan bool) {
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case req := <-service:
|
case req := <-service:
|
||||||
go run(op, req)
|
go run(op, req)
|
||||||
case <-quit:
|
case <-quit:
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -22,6 +22,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
.
|
.
|
||||||
.
|
.
|
||||||
|
@@ -10,10 +10,10 @@ var values = [5]int{10, 11, 12, 13, 14}
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// version A:
|
// version A:
|
||||||
for ix := range values { // ix is index!
|
for ix := range values { // ix is index!
|
||||||
func() {
|
func() {
|
||||||
fmt.Print(ix, " ")
|
fmt.Print(ix, " ")
|
||||||
}() // call closure, prints each index
|
}() // call closure, prints each index
|
||||||
}
|
}
|
||||||
fmt.Println()
|
fmt.Println()
|
||||||
// version B: same as A, but call closure as a goroutine
|
// version B: same as A, but call closure as a goroutine
|
||||||
@@ -25,20 +25,21 @@ func main() {
|
|||||||
time.Sleep(1e9)
|
time.Sleep(1e9)
|
||||||
// version C: the right way
|
// version C: the right way
|
||||||
for ix := range values {
|
for ix := range values {
|
||||||
go func(ix interface{}) {
|
go func(ix interface{}) {
|
||||||
fmt.Print(ix, " ")
|
fmt.Print(ix, " ")
|
||||||
}(ix)
|
}(ix)
|
||||||
}
|
}
|
||||||
time.Sleep(1e9)
|
time.Sleep(1e9)
|
||||||
// version D: print out the values:
|
// version D: print out the values:
|
||||||
for ix := range values {
|
for ix := range values {
|
||||||
val := values[ix]
|
val := values[ix]
|
||||||
go func() {
|
go func() {
|
||||||
fmt.Print(val, " ")
|
fmt.Print(val, " ")
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
time.Sleep(1e9)
|
time.Sleep(1e9)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
0 1 2 3 4
|
0 1 2 3 4
|
||||||
4 4 4 4 4
|
4 4 4 4 4
|
||||||
|
@@ -6,13 +6,12 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type nexter interface {
|
type nexter interface {
|
||||||
next() byte
|
next() byte
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
func nextFew1(n nexter, num int) []byte {
|
func nextFew1(n nexter, num int) []byte {
|
||||||
var b []byte
|
var b []byte
|
||||||
for i:=0; i < num; i++ {
|
for i := 0; i < num; i++ {
|
||||||
b[i] = n.next()
|
b[i] = n.next()
|
||||||
}
|
}
|
||||||
return b
|
return b
|
||||||
@@ -20,7 +19,7 @@ func nextFew1(n nexter, num int) []byte {
|
|||||||
|
|
||||||
func nextFew2(n *nexter, num int) []byte {
|
func nextFew2(n *nexter, num int) []byte {
|
||||||
var b []byte
|
var b []byte
|
||||||
for i:=0; i < num; i++ {
|
for i := 0; i < num; i++ {
|
||||||
b[i] = n.next() // compile error: n.next undefined (type *nexter has no field or method next)
|
b[i] = n.next() // compile error: n.next undefined (type *nexter has no field or method next)
|
||||||
}
|
}
|
||||||
return b
|
return b
|
||||||
|
@@ -11,6 +11,7 @@ URL: <input type="text" name="url">
|
|||||||
<input type="submit" value="Add">
|
<input type="submit" value="Add">
|
||||||
</form>
|
</form>
|
||||||
`
|
`
|
||||||
|
|
||||||
var store = NewURLStore()
|
var store = NewURLStore()
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -29,7 +30,6 @@ func Redirect(w http.ResponseWriter, r *http.Request) {
|
|||||||
http.Redirect(w, r, url, http.StatusFound)
|
http.Redirect(w, r, url, http.StatusFound)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
func Add(w http.ResponseWriter, r *http.Request) {
|
func Add(w http.ResponseWriter, r *http.Request) {
|
||||||
url := r.FormValue("url")
|
url := r.FormValue("url")
|
||||||
if url == "" {
|
if url == "" {
|
||||||
|
@@ -3,8 +3,8 @@ package main
|
|||||||
import "sync"
|
import "sync"
|
||||||
|
|
||||||
type URLStore struct {
|
type URLStore struct {
|
||||||
urls map[string]string
|
urls map[string]string
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewURLStore() *URLStore {
|
func NewURLStore() *URLStore {
|
||||||
|
@@ -23,7 +23,6 @@ func Redirect(w http.ResponseWriter, r *http.Request) {
|
|||||||
http.Redirect(w, r, url, http.StatusFound)
|
http.Redirect(w, r, url, http.StatusFound)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
func Add(w http.ResponseWriter, r *http.Request) {
|
func Add(w http.ResponseWriter, r *http.Request) {
|
||||||
url := r.FormValue("url")
|
url := r.FormValue("url")
|
||||||
if url == "" {
|
if url == "" {
|
||||||
|
@@ -9,9 +9,9 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type URLStore struct {
|
type URLStore struct {
|
||||||
urls map[string]string
|
urls map[string]string
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
file *os.File
|
file *os.File
|
||||||
}
|
}
|
||||||
|
|
||||||
type record struct {
|
type record struct {
|
||||||
|
@@ -1,7 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
// "bufio"
|
// "bufio"
|
||||||
"encoding/gob"
|
"encoding/gob"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
@@ -12,9 +12,9 @@ import (
|
|||||||
const saveQueueLength = 1000
|
const saveQueueLength = 1000
|
||||||
|
|
||||||
type URLStore struct {
|
type URLStore struct {
|
||||||
urls map[string]string
|
urls map[string]string
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
save chan record
|
save chan record
|
||||||
}
|
}
|
||||||
|
|
||||||
type record struct {
|
type record struct {
|
||||||
@@ -103,7 +103,7 @@ func (s *URLStore) saveLoop(filename string) {
|
|||||||
// e := gob.NewEncoder(b)
|
// e := gob.NewEncoder(b)
|
||||||
// defer b.Flush()
|
// defer b.Flush()
|
||||||
for {
|
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 {
|
if err := e.Encode(r); err != nil {
|
||||||
log.Println("Error saving to URLStore: ", err)
|
log.Println("Error saving to URLStore: ", err)
|
||||||
}
|
}
|
||||||
|
@@ -11,9 +11,9 @@ import (
|
|||||||
const saveQueueLength = 1000
|
const saveQueueLength = 1000
|
||||||
|
|
||||||
type URLStore struct {
|
type URLStore struct {
|
||||||
urls map[string]string
|
urls map[string]string
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
save chan record
|
save chan record
|
||||||
}
|
}
|
||||||
|
|
||||||
type record struct {
|
type record struct {
|
||||||
@@ -95,7 +95,7 @@ func (s *URLStore) saveLoop(filename string) {
|
|||||||
defer f.Close()
|
defer f.Close()
|
||||||
e := json.NewEncoder(f)
|
e := json.NewEncoder(f)
|
||||||
for {
|
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 {
|
if err := e.Encode(r); err != nil {
|
||||||
log.Println("Error saving to URLStore: ", err)
|
log.Println("Error saving to URLStore: ", err)
|
||||||
}
|
}
|
||||||
|
@@ -36,7 +36,7 @@ func main() {
|
|||||||
|
|
||||||
func Redirect(w http.ResponseWriter, r *http.Request) {
|
func Redirect(w http.ResponseWriter, r *http.Request) {
|
||||||
key := r.URL.Path[1:]
|
key := r.URL.Path[1:]
|
||||||
if key == "" {
|
if key == "" {
|
||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@@ -5,8 +5,8 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
|
||||||
"net/rpc"
|
"net/rpc"
|
||||||
|
"os"
|
||||||
"sync"
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -18,14 +18,14 @@ type Store interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ProxyStore struct {
|
type ProxyStore struct {
|
||||||
urls *URLStore // local cache
|
urls *URLStore // local cache
|
||||||
client *rpc.Client
|
client *rpc.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
type URLStore struct {
|
type URLStore struct {
|
||||||
urls map[string]string
|
urls map[string]string
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
save chan record
|
save chan record
|
||||||
}
|
}
|
||||||
|
|
||||||
type record struct {
|
type record struct {
|
||||||
|
@@ -4,4 +4,3 @@ package main
|
|||||||
func main() {
|
func main() {
|
||||||
println("Hello", "world")
|
println("Hello", "world")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -8,5 +8,6 @@ import (
|
|||||||
func main() {
|
func main() {
|
||||||
fmt.Printf("%s", runtime.Version())
|
fmt.Printf("%s", runtime.Version())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// go1.0.3 or go 1.1
|
// go1.0.3 or go 1.1
|
||||||
|
@@ -1,14 +1,14 @@
|
|||||||
package hello
|
package hello
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
http.HandleFunc("/", handler)
|
http.HandleFunc("/", handler)
|
||||||
}
|
}
|
||||||
|
|
||||||
func handler(w http.ResponseWriter, r *http.Request) {
|
func handler(w http.ResponseWriter, r *http.Request) {
|
||||||
fmt.Fprint(w, "Hello, world!")
|
fmt.Fprint(w, "Hello, world!")
|
||||||
}
|
}
|
||||||
|
@@ -1,28 +1,28 @@
|
|||||||
package hello
|
package hello
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"appengine"
|
"appengine"
|
||||||
"appengine/user"
|
"appengine/user"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
http.HandleFunc("/", handler)
|
http.HandleFunc("/", handler)
|
||||||
}
|
}
|
||||||
|
|
||||||
func handler(w http.ResponseWriter, r *http.Request) {
|
func handler(w http.ResponseWriter, r *http.Request) {
|
||||||
c := appengine.NewContext(r)
|
c := appengine.NewContext(r)
|
||||||
u := user.Current(c)
|
u := user.Current(c)
|
||||||
if u == nil {
|
if u == nil {
|
||||||
url, err := user.LoginURL(c, r.URL.String())
|
url, err := user.LoginURL(c, r.URL.String())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.String(), http.StatusInternalServerError)
|
http.Error(w, err.String(), http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
w.Header().Set("Location", url)
|
w.Header().Set("Location", url)
|
||||||
w.WriteHeader(http.StatusFound)
|
w.WriteHeader(http.StatusFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
fmt.Fprintf(w, "Hello, %v!", u)
|
fmt.Fprintf(w, "Hello, %v!", u)
|
||||||
}
|
}
|
||||||
|
@@ -1,9 +1,9 @@
|
|||||||
package hello
|
package hello
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"template"
|
"template"
|
||||||
)
|
)
|
||||||
|
|
||||||
const guestbookForm = `
|
const guestbookForm = `
|
||||||
@@ -24,23 +24,23 @@ const signTemplateHTML = `
|
|||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
`
|
`
|
||||||
|
|
||||||
var signTemplate = template.Must(template.New("sign").Parse(signTemplateHTML))
|
var signTemplate = template.Must(template.New("sign").Parse(signTemplateHTML))
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
http.HandleFunc("/", root)
|
http.HandleFunc("/", root)
|
||||||
http.HandleFunc("/sign", sign)
|
http.HandleFunc("/sign", sign)
|
||||||
}
|
}
|
||||||
|
|
||||||
func root(w http.ResponseWriter, r *http.Request) {
|
func root(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "text/html")
|
w.Header().Set("Content-Type", "text/html")
|
||||||
fmt.Fprint(w, guestbookForm)
|
fmt.Fprint(w, guestbookForm)
|
||||||
}
|
}
|
||||||
|
|
||||||
func sign(w http.ResponseWriter, r *http.Request) {
|
func sign(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "text/html")
|
w.Header().Set("Content-Type", "text/html")
|
||||||
err := signTemplate.Execute(w, r.FormValue("content"))
|
err := signTemplate.Execute(w, r.FormValue("content"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.String(), http.StatusInternalServerError)
|
http.Error(w, err.String(), http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -28,6 +28,7 @@ const guestbookTemplateHTML = `
|
|||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
`
|
`
|
||||||
|
|
||||||
var guestbookTemplate = template.Must(template.New("book").Parse(guestbookTemplateHTML))
|
var guestbookTemplate = template.Must(template.New("book").Parse(guestbookTemplateHTML))
|
||||||
|
|
||||||
type Greeting struct {
|
type Greeting struct {
|
||||||
|
@@ -13,4 +13,3 @@ func init() {
|
|||||||
func handle(w http.ResponseWriter, r *http.Request) {
|
func handle(w http.ResponseWriter, r *http.Request) {
|
||||||
fmt.Fprint(w, "<html><body>Hello, World! 세상아 안녕!! </body></html>")
|
fmt.Fprint(w, "<html><body>Hello, World! 세상아 안녕!! </body></html>")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -5,9 +5,9 @@ package rand
|
|||||||
import "C"
|
import "C"
|
||||||
|
|
||||||
func Random() int {
|
func Random() int {
|
||||||
return int(C.random())
|
return int(C.random())
|
||||||
}
|
}
|
||||||
|
|
||||||
func Seed(i int) {
|
func Seed(i int) {
|
||||||
C.srandom(C.uint(i))
|
C.srandom(C.uint(i))
|
||||||
}
|
}
|
||||||
|
@@ -7,7 +7,7 @@ import "C"
|
|||||||
import "unsafe"
|
import "unsafe"
|
||||||
|
|
||||||
func Print(s string) {
|
func Print(s string) {
|
||||||
cs := C.CString(s)
|
cs := C.CString(s)
|
||||||
defer C.free(unsafe.Pointer(cs))
|
defer C.free(unsafe.Pointer(cs))
|
||||||
C.fputs(cs, (*C.FILE)(C.stdout))
|
C.fputs(cs, (*C.FILE)(C.stdout))
|
||||||
}
|
}
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import fm "fmt" // alias
|
import fm "fmt" // alias
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
fm.Println("hello, world")
|
fm.Println("hello, world")
|
||||||
|
@@ -1,17 +1,19 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var n int16 = 34
|
var n int16 = 34
|
||||||
var m int32
|
var m int32
|
||||||
|
|
||||||
// compiler error: cannot use n (type int16) as type int32 in assignment
|
// compiler error: cannot use n (type int16) as type int32 in assignment
|
||||||
//m = n
|
//m = n
|
||||||
m = int32(n)
|
m = int32(n)
|
||||||
|
|
||||||
fmt.Printf("32 bit int is: %d\n", m)
|
fmt.Printf("32 bit int is: %d\n", m)
|
||||||
fmt.Printf("16 bit int is: %d\n", n)
|
fmt.Printf("16 bit int is: %d\n", n)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
32 bit int is: 34
|
32 bit int is: 34
|
||||||
16 bit int is: 34
|
16 bit int is: 34
|
||||||
|
@@ -14,6 +14,7 @@ func main() {
|
|||||||
fmt.Printf("%X - %X - %X\n", ch, ch2, ch3)
|
fmt.Printf("%X - %X - %X\n", ch, ch2, ch3)
|
||||||
fmt.Printf("%U - %U - %U", ch, ch2, ch3)
|
fmt.Printf("%U - %U - %U", ch, ch2, ch3)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Ouput:
|
/* Ouput:
|
||||||
65 - 946 - 1053236
|
65 - 946 - 1053236
|
||||||
A - β -
|
A - β -
|
||||||
|
@@ -1,5 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
var a string
|
var a string
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
a = "G"
|
a = "G"
|
||||||
print(a)
|
print(a)
|
||||||
|
@@ -1,5 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
var a = "G"
|
var a = "G"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
n()
|
n()
|
||||||
m()
|
m()
|
||||||
|
@@ -1,5 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
var a = "G"
|
var a = "G"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
n()
|
n()
|
||||||
m()
|
m()
|
||||||
|
@@ -11,4 +11,5 @@ func main() {
|
|||||||
fmt.Printf("T/F? Does the string \"%s\" have prefix %s? ", str, "Th")
|
fmt.Printf("T/F? Does the string \"%s\" have prefix %s? ", str, "Th")
|
||||||
fmt.Printf("%t\n", strings.HasPrefix(str, "Th"))
|
fmt.Printf("%t\n", strings.HasPrefix(str, "Th"))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Output: T/F? Does the string "This is an example of a string" have prefix Th? true
|
// Output: T/F? Does the string "This is an example of a string" have prefix Th? true
|
@@ -22,6 +22,7 @@ func main() {
|
|||||||
fmt.Printf("%2.2f / ", 100*rand.Float32())
|
fmt.Printf("%2.2f / ", 100*rand.Float32())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
134020434 / 1597969999 / 1721070109 / 2068675587 / 1237770961 / 220031192 / 2031484958 / 583324308 / 958990240 / 413002649 / 6 / 7 / 2 / 1 / 0 /
|
134020434 / 1597969999 / 1721070109 / 2068675587 / 1237770961 / 220031192 / 2031484958 / 583324308 / 958990240 / 413002649 / 6 / 7 / 2 / 1 / 0 /
|
||||||
22.84 / 10.12 / 44.32 / 58.58 / 15.49 / 12.23 / 30.16 / 88.48 / 34.26 / 27.18 /
|
22.84 / 10.12 / 44.32 / 58.58 / 15.49 / 12.23 / 30.16 / 88.48 / 34.26 / 27.18 /
|
||||||
|
@@ -21,9 +21,10 @@ func main() {
|
|||||||
fmt.Printf("%s - ", val)
|
fmt.Printf("%s - ", val)
|
||||||
}
|
}
|
||||||
fmt.Println()
|
fmt.Println()
|
||||||
str3 := strings.Join(sl2,";")
|
str3 := strings.Join(sl2, ";")
|
||||||
fmt.Printf("sl2 joined by ;: %s\n", str3)
|
fmt.Printf("sl2 joined by ;: %s\n", str3)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
Splitted in slice: [The quick brown fox jumps over the lazy dog]
|
Splitted in slice: [The quick brown fox jumps over the lazy dog]
|
||||||
The - quick - brown - fox - jumps - over - the - lazy - dog -
|
The - quick - brown - fox - jumps - over - the - lazy - dog -
|
||||||
|
@@ -7,5 +7,6 @@ func main() {
|
|||||||
*p = 0
|
*p = 0
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// in Windows: stops only with: <exit code="-1073741819" msg="process crashed"/>
|
// in Windows: stops only with: <exit code="-1073741819" msg="process crashed"/>
|
||||||
// runtime error: invalid memory address or nil pointer dereference
|
// runtime error: invalid memory address or nil pointer dereference
|
||||||
|
@@ -9,18 +9,18 @@ var week time.Duration
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
t := time.Now()
|
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
|
fmt.Printf("%02d.%02d.%4d\n", t.Day(), t.Month(), t.Year()) // 21.12.2011
|
||||||
t = time.Now().UTC()
|
t = time.Now().UTC()
|
||||||
fmt.Println(t) // Wed Dec 21 08:52:14 +0000 UTC 2011
|
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
|
fmt.Println(time.Now()) // Wed Dec 21 09:52:14 +0100 RST 2011
|
||||||
// calculating times:
|
// 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)
|
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:
|
// formatting times:
|
||||||
fmt.Println(t.Format(time.RFC822)) // 21 Dec 11 0852 UTC
|
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.ANSIC)) // Wed Dec 21 08:56:34 2011
|
||||||
fmt.Println(t.Format("02 Jan 2006 15:04")) // 21 Dec 2011 08:52
|
fmt.Println(t.Format("02 Jan 2006 15:04")) // 21 Dec 2011 08:52
|
||||||
s := t.Format("20060102")
|
s := t.Format("20060102")
|
||||||
fmt.Println(t, "=>", s) // Wed Dec 21 08:52:14 +0000 UTC 2011 => 20111221
|
fmt.Println(t, "=>", s) // Wed Dec 21 08:52:14 +0000 UTC 2011 => 20111221
|
||||||
|
@@ -4,6 +4,6 @@ func main() {
|
|||||||
var a int
|
var a int
|
||||||
var b int32
|
var b int32
|
||||||
a = 15
|
a = 15
|
||||||
b = a + a // compiler error
|
b = a + a // compiler error
|
||||||
b = b + 5 // ok: 5 is a constant
|
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