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 chapter 11, 12, 13, 14 and 15.
This commit is contained in:
@@ -1,12 +1,12 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"./float64"
|
||||||
"./float64"
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
f1 := float64.NewFloat64Array()
|
f1 := float64.NewFloat64Array()
|
||||||
f1.Fill(10)
|
f1.Fill(10)
|
||||||
fmt.Printf("Before sorting %s\n", f1)
|
fmt.Printf("Before sorting %s\n", f1)
|
||||||
float64.Sort(f1)
|
float64.Sort(f1)
|
||||||
|
@@ -3,8 +3,8 @@ package main
|
|||||||
|
|
||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
type Any interface {}
|
type Any interface{}
|
||||||
type Anything struct {}
|
type Anything struct{}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
any := getAny()
|
any := getAny()
|
||||||
@@ -13,15 +13,15 @@ func main() {
|
|||||||
} else {
|
} else {
|
||||||
fmt.Println("any is not nil")
|
fmt.Println("any is not nil")
|
||||||
}
|
}
|
||||||
/*
|
/*
|
||||||
// to get the inner value:
|
// to get the inner value:
|
||||||
anything := any.(*Anything)
|
anything := any.(*Anything)
|
||||||
if anything == nil {
|
if anything == nil {
|
||||||
fmt.Println("anything is nil")
|
fmt.Println("anything is nil")
|
||||||
} else {
|
} else {
|
||||||
fmt.Println("anything is not nil")
|
fmt.Println("anything is not nil")
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
func getAny() Any {
|
func getAny() Any {
|
||||||
|
@@ -10,7 +10,8 @@ type Shaper interface {
|
|||||||
Area() float32
|
Area() float32
|
||||||
}
|
}
|
||||||
|
|
||||||
type Shape struct {}
|
type Shape struct{}
|
||||||
|
|
||||||
func (sh Shape) Area() float32 {
|
func (sh Shape) Area() float32 {
|
||||||
return -1 // the shape is indetermined, so we return something impossible
|
return -1 // the shape is indetermined, so we return something impossible
|
||||||
}
|
}
|
||||||
@@ -25,12 +26,12 @@ func (sq *Square) Area() float32 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Rectangle struct {
|
type Rectangle struct {
|
||||||
length, width float32
|
length, width float32
|
||||||
Shape
|
Shape
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Rectangle) Area() float32 {
|
func (r *Rectangle) Area() float32 {
|
||||||
return r.length * r.width
|
return r.length * r.width
|
||||||
}
|
}
|
||||||
|
|
||||||
type Circle struct {
|
type Circle struct {
|
||||||
@@ -39,21 +40,22 @@ type Circle struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Circle) Area() float32 {
|
func (c *Circle) Area() float32 {
|
||||||
return math.Pi * c.radius * c.radius
|
return math.Pi * c.radius * c.radius
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
s := Shape{}
|
s := Shape{}
|
||||||
r := &Rectangle{5, 3, s} // Area() of Rectangle needs a value
|
r := &Rectangle{5, 3, s} // Area() of Rectangle needs a value
|
||||||
q := &Square{5, s} // Area() of Square needs a pointer
|
q := &Square{5, s} // Area() of Square needs a pointer
|
||||||
c := &Circle{2.5, s}
|
c := &Circle{2.5, s}
|
||||||
shapes := []Shaper{r, q, c, s}
|
shapes := []Shaper{r, q, c, s}
|
||||||
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}
|
||||||
@@ -65,4 +67,3 @@ Area of this shape is: 19.634954
|
|||||||
Shape details: {}
|
Shape details: {}
|
||||||
Area of this shape is: -1
|
Area of this shape is: -1
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
@@ -18,6 +18,7 @@ type AreaInterface interface {
|
|||||||
type PeriInterface interface {
|
type PeriInterface interface {
|
||||||
Perimeter() float32
|
Perimeter() float32
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var areaIntf AreaInterface
|
var areaIntf AreaInterface
|
||||||
var periIntf PeriInterface
|
var periIntf PeriInterface
|
||||||
@@ -47,5 +48,5 @@ func (sq *Square) Perimeter() float32 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (tr *Triangle) Area() float32 {
|
func (tr *Triangle) Area() float32 {
|
||||||
return 0.5 * tr.base*tr.height
|
return 0.5 * tr.base * tr.height
|
||||||
}
|
}
|
||||||
|
@@ -19,11 +19,11 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
type Circle struct {
|
type Circle struct {
|
||||||
@@ -31,21 +31,22 @@ type Circle struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Circle) Area() float32 {
|
func (c *Circle) Area() float32 {
|
||||||
return math.Pi * c.radius * c.radius
|
return math.Pi * c.radius * c.radius
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
||||||
c := &Circle{2.5}
|
c := &Circle{2.5}
|
||||||
fmt.Println("Looping through shapes for area ...")
|
fmt.Println("Looping through shapes for area ...")
|
||||||
// shapes := []Shaper{Shaper(r), Shaper(q), Shaper(c)}
|
// shapes := []Shaper{Shaper(r), Shaper(q), Shaper(c)}
|
||||||
shapes := []Shaper{r, q, c}
|
shapes := []Shaper{r, q, c}
|
||||||
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}
|
||||||
|
@@ -2,8 +2,8 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"./stack/stack"
|
"./stack/stack"
|
||||||
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
var st1 stack.Stack
|
var st1 stack.Stack
|
||||||
@@ -21,6 +21,7 @@ func main() {
|
|||||||
fmt.Println(item)
|
fmt.Println(item)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
[Java C++ Python C# Ruby]
|
[Java C++ Python C# Ruby]
|
||||||
100
|
100
|
||||||
|
@@ -2,16 +2,16 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"./stack/collection"
|
"./stack/collection"
|
||||||
"fmt"
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var s collection.Stack
|
var s collection.Stack
|
||||||
s.Push("world")
|
s.Push("world")
|
||||||
s.Push("hello, ")
|
s.Push("hello, ")
|
||||||
for s.Size() > 0 {
|
for s.Size() > 0 {
|
||||||
fmt.Print(s.Pop())
|
fmt.Print(s.Pop())
|
||||||
}
|
}
|
||||||
fmt.Println()
|
fmt.Println()
|
||||||
}
|
}
|
@@ -8,10 +8,10 @@ func main() {
|
|||||||
// define a generic lambda function mf:
|
// define a generic lambda function mf:
|
||||||
mf := func(i obj) obj {
|
mf := func(i obj) obj {
|
||||||
switch i.(type) {
|
switch i.(type) {
|
||||||
case int:
|
case int:
|
||||||
return i.(int) * 2
|
return i.(int) * 2
|
||||||
case string:
|
case string:
|
||||||
return i.(string) + i.(string)
|
return i.(string) + i.(string)
|
||||||
}
|
}
|
||||||
return i
|
return i
|
||||||
}
|
}
|
||||||
@@ -30,7 +30,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func mapFunc(mf func(obj) obj, list []obj) ([]obj) {
|
func mapFunc(mf func(obj) obj, list []obj) []obj {
|
||||||
result := make([]obj, len(list))
|
result := make([]obj, len(list))
|
||||||
|
|
||||||
for ix, v := range list {
|
for ix, v := range list {
|
||||||
@@ -39,12 +39,13 @@ func mapFunc(mf func(obj) obj, list []obj) ([]obj) {
|
|||||||
|
|
||||||
// Equivalent:
|
// Equivalent:
|
||||||
/*
|
/*
|
||||||
for ix := 0; ix<len(list); ix++ {
|
for ix := 0; ix<len(list); ix++ {
|
||||||
result[ix] = mf(list[ix])
|
result[ix] = mf(list[ix])
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
0
|
0
|
||||||
2
|
2
|
||||||
|
@@ -8,10 +8,10 @@ func main() {
|
|||||||
// define a generic lambda function mf:
|
// define a generic lambda function mf:
|
||||||
mf := func(i obj) obj {
|
mf := func(i obj) obj {
|
||||||
switch i.(type) {
|
switch i.(type) {
|
||||||
case int:
|
case int:
|
||||||
return i.(int) * 2
|
return i.(int) * 2
|
||||||
case string:
|
case string:
|
||||||
return i.(string) + i.(string)
|
return i.(string) + i.(string)
|
||||||
}
|
}
|
||||||
return i
|
return i
|
||||||
}
|
}
|
||||||
@@ -27,7 +27,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func mapFunc(mf func(obj) obj, list ...obj) ([]obj) {
|
func mapFunc(mf func(obj) obj, list ...obj) []obj {
|
||||||
result := make([]obj, len(list))
|
result := make([]obj, len(list))
|
||||||
|
|
||||||
for ix, v := range list {
|
for ix, v := range list {
|
||||||
@@ -36,12 +36,13 @@ func mapFunc(mf func(obj) obj, list ...obj) ([]obj) {
|
|||||||
|
|
||||||
// Equivalent:
|
// Equivalent:
|
||||||
/*
|
/*
|
||||||
for ix := 0; ix<len(list); ix++ {
|
for ix := 0; ix<len(list); ix++ {
|
||||||
result[ix] = mf(list[ix])
|
result[ix] = mf(list[ix])
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
0
|
0
|
||||||
2
|
2
|
||||||
|
@@ -7,22 +7,24 @@ type Miner interface {
|
|||||||
Less(i, j int) bool
|
Less(i, j int) bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func Min(data Miner) interface{} {
|
func Min(data Miner) interface{} {
|
||||||
min := data.ElemIx(0)
|
min := data.ElemIx(0)
|
||||||
for i:=1; i < data.Len(); i++ {
|
for i := 1; i < data.Len(); i++ {
|
||||||
if data.Less(i, i-1) {
|
if data.Less(i, i-1) {
|
||||||
min = data.ElemIx(i)
|
min = data.ElemIx(i)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return min
|
return min
|
||||||
}
|
}
|
||||||
|
|
||||||
type IntArray []int
|
type IntArray []int
|
||||||
func (p IntArray) Len() int { return len(p) }
|
|
||||||
func (p IntArray) ElemIx(ix int) interface{} { return p[ix] }
|
func (p IntArray) Len() int { return len(p) }
|
||||||
func (p IntArray) Less(i, j int) bool { return p[i] < p[j] }
|
func (p IntArray) ElemIx(ix int) interface{} { return p[ix] }
|
||||||
|
func (p IntArray) Less(i, j int) bool { return p[i] < p[j] }
|
||||||
|
|
||||||
type StringArray []string
|
type StringArray []string
|
||||||
func (p StringArray) Len() int { return len(p) }
|
|
||||||
func (p StringArray) ElemIx(ix int) interface{} { return p[ix] }
|
func (p StringArray) Len() int { return len(p) }
|
||||||
func (p StringArray) Less(i, j int) bool { return p[i] < p[j] }
|
func (p StringArray) ElemIx(ix int) interface{} { return p[ix] }
|
||||||
|
func (p StringArray) Less(i, j int) bool { return p[i] < p[j] }
|
||||||
|
@@ -2,27 +2,27 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"./min"
|
||||||
"./min"
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
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 := min.IntArray(data) //conversion to type IntArray
|
a := min.IntArray(data) //conversion to type IntArray
|
||||||
m := min.Min(a)
|
m := min.Min(a)
|
||||||
fmt.Printf("The minimum of the array is: %v\n", m)
|
fmt.Printf("The minimum of the array is: %v\n", m)
|
||||||
}
|
}
|
||||||
|
|
||||||
func strings() {
|
func strings() {
|
||||||
data := []string{"ddd", "eee", "bbb", "ccc", "aaa"}
|
data := []string{"ddd", "eee", "bbb", "ccc", "aaa"}
|
||||||
a := min.StringArray(data)
|
a := min.StringArray(data)
|
||||||
m := min.Min(a)
|
m := min.Min(a)
|
||||||
fmt.Printf("The minimum of the array is: %v\n", m)
|
fmt.Printf("The minimum of the array is: %v\n", m)
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
ints()
|
ints()
|
||||||
strings()
|
strings()
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
|
@@ -46,13 +46,13 @@ func main() {
|
|||||||
m = p1 // p1 is type *Point, has method Abs()
|
m = p1 // p1 is type *Point, has method Abs()
|
||||||
fmt.Printf("The length of the vector p1 is: %f\n", m.Abs())
|
fmt.Printf("The length of the vector p1 is: %f\n", m.Abs())
|
||||||
|
|
||||||
p2:= &Point{4, 5}
|
p2 := &Point{4, 5}
|
||||||
m = p2
|
m = p2
|
||||||
fmt.Printf("The length of the vector p2 is: %f\n", m.Abs() )
|
fmt.Printf("The length of the vector p2 is: %f\n", m.Abs())
|
||||||
|
|
||||||
p1.Scale(5)
|
p1.Scale(5)
|
||||||
m = p1
|
m = p1
|
||||||
fmt.Printf("The length of the vector p1 after scaling is: %f\n", m.Abs() )
|
fmt.Printf("The length of the vector p1 after scaling is: %f\n", m.Abs())
|
||||||
fmt.Printf("Point p1 after scaling has the following coordinates: X %f - Y %f\n", p1.X, p1.Y)
|
fmt.Printf("Point p1 after scaling has the following coordinates: X %f - Y %f\n", p1.X, p1.Y)
|
||||||
|
|
||||||
mag := m.Abs()
|
mag := m.Abs()
|
||||||
@@ -60,8 +60,9 @@ func main() {
|
|||||||
mag += m.Abs()
|
mag += m.Abs()
|
||||||
m = Polar{2.0, math.Pi / 2}
|
m = Polar{2.0, math.Pi / 2}
|
||||||
mag += m.Abs()
|
mag += m.Abs()
|
||||||
fmt.Printf("The float64 mag is now: %f", mag )
|
fmt.Printf("The float64 mag is now: %f", mag)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
The length of the vector p1 is: 5.000000
|
The length of the vector p1 is: 5.000000
|
||||||
The length of the vector p2 is: 6.403124
|
The length of the vector p2 is: 6.403124
|
||||||
|
@@ -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
|
@@ -29,6 +29,7 @@ func fI(it Simpler) int {
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var s Simple
|
var s Simple
|
||||||
fmt.Println(fI(&s)) // &s is required because Get() is defined with a receiver type pointer
|
fmt.Println(fI(&s)) // &s is required because Get() is defined with a receiver type pointer
|
||||||
}
|
}
|
||||||
|
|
||||||
// Output: 5
|
// Output: 5
|
@@ -38,23 +38,24 @@ func (p *RSimple) Set(u int) {
|
|||||||
func fI(it Simpler) int {
|
func fI(it Simpler) int {
|
||||||
switch it.(type) {
|
switch it.(type) {
|
||||||
case *Simple:
|
case *Simple:
|
||||||
it.Set(5)
|
it.Set(5)
|
||||||
return it.Get()
|
return it.Get()
|
||||||
case *RSimple:
|
case *RSimple:
|
||||||
it.Set(50)
|
it.Set(50)
|
||||||
return it.Get()
|
return it.Get()
|
||||||
default:
|
default:
|
||||||
return 99
|
return 99
|
||||||
}
|
}
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var s Simple
|
var s Simple
|
||||||
fmt.Println(fI(&s)) // &s is required because Get() is defined with a receiver type pointer
|
fmt.Println(fI(&s)) // &s is required because Get() is defined with a receiver type pointer
|
||||||
var r RSimple
|
var r RSimple
|
||||||
fmt.Println(fI(&r))
|
fmt.Println(fI(&r))
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
5
|
5
|
||||||
50
|
50
|
||||||
|
@@ -38,25 +38,25 @@ func (p *RSimple) Set(u int) {
|
|||||||
func fI(it Simpler) int {
|
func fI(it Simpler) int {
|
||||||
switch it.(type) {
|
switch it.(type) {
|
||||||
case *Simple:
|
case *Simple:
|
||||||
it.Set(5)
|
it.Set(5)
|
||||||
return it.Get()
|
return it.Get()
|
||||||
case *RSimple:
|
case *RSimple:
|
||||||
it.Set(50)
|
it.Set(50)
|
||||||
return it.Get()
|
return it.Get()
|
||||||
default:
|
default:
|
||||||
return 99
|
return 99
|
||||||
}
|
}
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
func gI(any interface{}) int {
|
func gI(any interface{}) int {
|
||||||
// return any.(Simpler).Get() // unsafe, runtime panic possible
|
// return any.(Simpler).Get() // unsafe, runtime panic possible
|
||||||
if v, ok := any.(Simpler); ok {
|
if v, ok := any.(Simpler); ok {
|
||||||
return v.Get()
|
return v.Get()
|
||||||
}
|
}
|
||||||
return 0 // default value
|
return 0 // default value
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
6
|
6
|
||||||
60
|
60
|
||||||
@@ -64,10 +64,11 @@ func gI(any interface{}) int {
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var s Simple = Simple{6}
|
var s Simple = Simple{6}
|
||||||
fmt.Println(gI(&s)) // &s is required because Get() is defined with a receiver type pointer
|
fmt.Println(gI(&s)) // &s is required because Get() is defined with a receiver type pointer
|
||||||
var r RSimple = RSimple{60,60}
|
var r RSimple = RSimple{60, 60}
|
||||||
fmt.Println(gI(&r))
|
fmt.Println(gI(&r))
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
6
|
6
|
||||||
60
|
60
|
||||||
|
@@ -20,8 +20,8 @@ func Sort(Sorter Interface) {
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
func Sort(data Sorter) {
|
func Sort(data Sorter) {
|
||||||
for pass:=1; pass < data.Len(); pass++ {
|
for pass := 1; pass < data.Len(); pass++ {
|
||||||
for i:=0; i < data.Len() - pass; i++ {
|
for i := 0; i < data.Len()-pass; i++ {
|
||||||
if data.Less(i+1, i) {
|
if data.Less(i+1, i) {
|
||||||
data.Swap(i, i+1)
|
data.Swap(i, i+1)
|
||||||
}
|
}
|
||||||
@@ -53,8 +53,8 @@ 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] }
|
||||||
|
|
||||||
// Convenience wrappers for common cases
|
// Convenience wrappers for common cases
|
||||||
func SortInts(a []int) { Sort(IntArray(a)) }
|
func SortInts(a []int) { Sort(IntArray(a)) }
|
||||||
func SortStrings(a []string) { Sort(StringArray(a)) }
|
func SortStrings(a []string) { Sort(StringArray(a)) }
|
||||||
|
|
||||||
func IntsAreSorted(a []int) bool { return IsSorted(IntArray(a)) }
|
func IntsAreSorted(a []int) bool { return IsSorted(IntArray(a)) }
|
||||||
func StringsAreSorted(a []string) bool { return IsSorted(StringArray(a)) }
|
func StringsAreSorted(a []string) bool { return IsSorted(StringArray(a)) }
|
||||||
|
@@ -2,8 +2,8 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"./sort"
|
"./sort"
|
||||||
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Person struct {
|
type Person struct {
|
||||||
@@ -21,15 +21,15 @@ func (p Persons) Less(i, j int) bool {
|
|||||||
return in < jn
|
return in < jn
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p Persons) Swap(i, j int) {
|
func (p Persons) Swap(i, j int) {
|
||||||
p[i], p[j] = p[j], p[i]
|
p[i], p[j] = p[j], p[i]
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
p1 := Person{"Xavier","Papadopoulos"}
|
p1 := Person{"Xavier", "Papadopoulos"}
|
||||||
p2 := Person{"Chris","Naegels"}
|
p2 := Person{"Chris", "Naegels"}
|
||||||
p3 := Person{"John","Doe"}
|
p3 := Person{"John", "Doe"}
|
||||||
arrP := Persons{p1,p2,p3}
|
arrP := Persons{p1, p2, p3}
|
||||||
fmt.Printf("Before sorting: %v\n", arrP)
|
fmt.Printf("Before sorting: %v\n", arrP)
|
||||||
sort.Sort(arrP)
|
sort.Sort(arrP)
|
||||||
fmt.Printf("After sorting: %v\n", arrP)
|
fmt.Printf("After sorting: %v\n", arrP)
|
||||||
|
@@ -29,7 +29,7 @@ func (stack Stack) Top() (interface{}, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (stack *Stack) Pop() (interface{}, error) {
|
func (stack *Stack) Pop() (interface{}, error) {
|
||||||
stk := *stack // dereference to a local variable stk
|
stk := *stack // dereference to a local variable stk
|
||||||
if len(stk) == 0 {
|
if len(stk) == 0 {
|
||||||
return nil, errors.New("stack is empty")
|
return nil, errors.New("stack is empty")
|
||||||
}
|
}
|
||||||
|
@@ -4,25 +4,25 @@ package collection
|
|||||||
|
|
||||||
// The zero value for Stack is an empty stack ready to use.
|
// The zero value for Stack is an empty stack ready to use.
|
||||||
type Stack struct {
|
type Stack struct {
|
||||||
data []interface{}
|
data []interface{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Push adds x to the top of the stack.
|
// Push adds x to the top of the stack.
|
||||||
func (s *Stack) Push(x interface{}) {
|
func (s *Stack) Push(x interface{}) {
|
||||||
s.data = append(s.data, x)
|
s.data = append(s.data, x)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pop removes and returns the top element of the stack.
|
// Pop removes and returns the top element of the stack.
|
||||||
// It's a run-time error to call Pop on an empty stack.
|
// It's a run-time error to call Pop on an empty stack.
|
||||||
func (s *Stack) Pop() interface{} {
|
func (s *Stack) Pop() interface{} {
|
||||||
i := len(s.data) - 1
|
i := len(s.data) - 1
|
||||||
res := s.data[i]
|
res := s.data[i]
|
||||||
s.data[i] = nil // to avoid memory leak
|
s.data[i] = nil // to avoid memory leak
|
||||||
s.data = s.data[:i]
|
s.data = s.data[:i]
|
||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
|
|
||||||
// Size returns the number of elements in the stack.
|
// Size returns the number of elements in the stack.
|
||||||
func (s *Stack) Size() int {
|
func (s *Stack) Size() int {
|
||||||
return len(s.data)
|
return len(s.data)
|
||||||
}
|
}
|
@@ -4,11 +4,11 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"strconv"
|
|
||||||
"bufio"
|
|
||||||
"os"
|
|
||||||
"./stack/stack"
|
"./stack/stack"
|
||||||
|
"bufio"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -21,35 +21,35 @@ func main() {
|
|||||||
fmt.Println("Input error !")
|
fmt.Println("Input error !")
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
token = token[0:len(token)-2] // remove "\r\n"
|
token = token[0 : len(token)-2] // remove "\r\n"
|
||||||
// fmt.Printf("--%s--\n",token) // debug statement
|
// fmt.Printf("--%s--\n",token) // debug statement
|
||||||
switch {
|
switch {
|
||||||
case token == "q": // stop als invoer = "q"
|
case token == "q": // stop als invoer = "q"
|
||||||
fmt.Println("Calculator stopped")
|
fmt.Println("Calculator stopped")
|
||||||
return
|
return
|
||||||
case token >= "0" && token <= "999999":
|
case token >= "0" && token <= "999999":
|
||||||
i, _ := strconv.Atoi(token)
|
i, _ := strconv.Atoi(token)
|
||||||
calc1.Push(i)
|
calc1.Push(i)
|
||||||
case token == "+":
|
case token == "+":
|
||||||
q, _ := calc1.Pop()
|
q, _ := calc1.Pop()
|
||||||
p, _ := calc1.Pop()
|
p, _ := calc1.Pop()
|
||||||
fmt.Printf("The result of %d %s %d = %d\n", p, token, q, p.(int) + q.(int))
|
fmt.Printf("The result of %d %s %d = %d\n", p, token, q, p.(int)+q.(int))
|
||||||
case token == "-":
|
case token == "-":
|
||||||
q, _ := calc1.Pop()
|
q, _ := calc1.Pop()
|
||||||
p, _ := calc1.Pop()
|
p, _ := calc1.Pop()
|
||||||
fmt.Printf("The result of %d %s %d = %d\n", p, token, q, p.(int) - q.(int))
|
fmt.Printf("The result of %d %s %d = %d\n", p, token, q, p.(int)-q.(int))
|
||||||
|
|
||||||
case token == "*":
|
case token == "*":
|
||||||
q, _ := calc1.Pop()
|
q, _ := calc1.Pop()
|
||||||
p, _ := calc1.Pop()
|
p, _ := calc1.Pop()
|
||||||
fmt.Printf("The result of %d %s %d = %d\n", p, token, q, p.(int) * q.(int))
|
fmt.Printf("The result of %d %s %d = %d\n", p, token, q, p.(int)*q.(int))
|
||||||
|
|
||||||
case token == "/":
|
case token == "/":
|
||||||
q, _ := calc1.Pop()
|
q, _ := calc1.Pop()
|
||||||
p, _ := calc1.Pop()
|
p, _ := calc1.Pop()
|
||||||
fmt.Printf("The result of %d %s %d = %d\n", p, token, q, p.(int) / q.(int))
|
fmt.Printf("The result of %d %s %d = %d\n", p, token, q, p.(int)/q.(int))
|
||||||
default:
|
default:
|
||||||
fmt.Println("No valid input")
|
fmt.Println("No valid input")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,11 +1,11 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
|
||||||
"io"
|
|
||||||
"fmt"
|
|
||||||
"bufio"
|
"bufio"
|
||||||
"flag"
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
var numberFlag = flag.Bool("n", false, "number each line")
|
var numberFlag = flag.Bool("n", false, "number each line")
|
||||||
|
@@ -3,30 +3,30 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"fmt"
|
|
||||||
"encoding/gob"
|
"encoding/gob"
|
||||||
|
"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
|
||||||
}
|
}
|
||||||
|
|
||||||
var content string
|
var content string
|
||||||
var vc VCard
|
var vc VCard
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// using a decoder:
|
// using a decoder:
|
||||||
file, _ := os.Open("vcard.gob")
|
file, _ := os.Open("vcard.gob")
|
||||||
defer file.Close()
|
defer file.Close()
|
||||||
inReader := bufio.NewReader(file)
|
inReader := bufio.NewReader(file)
|
||||||
@@ -37,5 +37,6 @@ func main() {
|
|||||||
}
|
}
|
||||||
fmt.Println(vc)
|
fmt.Println(vc)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// {Jan Kersschot [0x12642e60 0x12642e80] none}
|
// {Jan Kersschot [0x12642e60 0x12642e80] none}
|
@@ -2,18 +2,19 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt";
|
"crypto/md5"
|
||||||
"crypto/md5"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
hasher := md5.New()
|
hasher := md5.New()
|
||||||
b := []byte{}
|
b := []byte{}
|
||||||
io.WriteString(hasher, "test")
|
io.WriteString(hasher, "test")
|
||||||
fmt.Printf("Result: %x\n", hasher.Sum(b))
|
fmt.Printf("Result: %x\n", hasher.Sum(b))
|
||||||
fmt.Printf("Result: %d\n", hasher.Sum(b))
|
fmt.Printf("Result: %d\n", hasher.Sum(b))
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
Result: 098f6bcd4621d373cade4e832627b4f6
|
Result: 098f6bcd4621d373cade4e832627b4f6
|
||||||
Result: [9 143 107 205 70 33 211 115 202 222 78 131 38 39 180 246]
|
Result: [9 143 107 205 70 33 211 115 202 222 78 131 38 39 180 246]
|
||||||
|
@@ -4,17 +4,17 @@ package main
|
|||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
|
||||||
"io"
|
"io"
|
||||||
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Book struct {
|
type Book struct {
|
||||||
title string
|
title string
|
||||||
price float64
|
price float64
|
||||||
quantity int
|
quantity int
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -40,12 +40,12 @@ func main() {
|
|||||||
book := new(Book)
|
book := new(Book)
|
||||||
book.title = strSl[0]
|
book.title = strSl[0]
|
||||||
book.price, err = strconv.ParseFloat(strSl[1], 32)
|
book.price, err = strconv.ParseFloat(strSl[1], 32)
|
||||||
if err!=nil {
|
if err != nil {
|
||||||
fmt.Printf("Error in file: %v", err)
|
fmt.Printf("Error in file: %v", err)
|
||||||
}
|
}
|
||||||
//fmt.Printf("The quan was:-%s-", strSl[2])
|
//fmt.Printf("The quan was:-%s-", strSl[2])
|
||||||
book.quantity, err = strconv.Atoi(strSl[2])
|
book.quantity, err = strconv.Atoi(strSl[2])
|
||||||
if err!=nil {
|
if err != nil {
|
||||||
fmt.Printf("Error in file: %v", err)
|
fmt.Printf("Error in file: %v", err)
|
||||||
}
|
}
|
||||||
if bks[0].title == "" {
|
if bks[0].title == "" {
|
||||||
@@ -59,6 +59,7 @@ func main() {
|
|||||||
fmt.Println(bk)
|
fmt.Println(bk)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
We have read the following books from the file:
|
We have read the following books from the file:
|
||||||
{"The ABC of Go" 25.5 1500}
|
{"The ABC of Go" 25.5 1500}
|
||||||
|
@@ -2,9 +2,9 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bufio"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"bufio"
|
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -27,7 +27,7 @@ func main() {
|
|||||||
//fmt.Printf("The output was: --%s--", outputString)
|
//fmt.Printf("The output was: --%s--", outputString)
|
||||||
_, err := outputWriter.WriteString(outputString)
|
_, err := outputWriter.WriteString(outputString)
|
||||||
//fmt.Printf("Number of bytes written %d\n", n)
|
//fmt.Printf("Number of bytes written %d\n", n)
|
||||||
if (err != nil) {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@@ -2,16 +2,17 @@
|
|||||||
package stack
|
package stack
|
||||||
|
|
||||||
import "strconv"
|
import "strconv"
|
||||||
|
|
||||||
const LIMIT = 10
|
const LIMIT = 10
|
||||||
|
|
||||||
type Stack struct {
|
type Stack struct {
|
||||||
ix int // first free position, so data[ix] == 0
|
ix int // first free position, so data[ix] == 0
|
||||||
data [LIMIT]int
|
data [LIMIT]int
|
||||||
}
|
}
|
||||||
|
|
||||||
func (st *Stack) Push(n int) {
|
func (st *Stack) Push(n int) {
|
||||||
if (st.ix + 1 > LIMIT) {
|
if st.ix+1 > LIMIT {
|
||||||
return // stack is full!
|
return // stack is full!
|
||||||
}
|
}
|
||||||
st.data[st.ix] = n
|
st.data[st.ix] = n
|
||||||
st.ix++
|
st.ix++
|
||||||
@@ -24,9 +25,8 @@ func (st *Stack) Pop() int {
|
|||||||
|
|
||||||
func (st Stack) String() string {
|
func (st Stack) String() string {
|
||||||
str := ""
|
str := ""
|
||||||
for ix:=0; ix<st.ix; ix++ {
|
for ix := 0; ix < st.ix; ix++ {
|
||||||
str += "[" + strconv.Itoa(ix) + ":" + strconv.Itoa(st.data[ix]) + "] "
|
str += "[" + strconv.Itoa(ix) + ":" + strconv.Itoa(st.data[ix]) + "] "
|
||||||
}
|
}
|
||||||
return str
|
return str
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -33,6 +33,7 @@ func main() {
|
|||||||
new_page.load("Page.md")
|
new_page.load("Page.md")
|
||||||
fmt.Println(string(new_page.Body))
|
fmt.Println(string(new_page.Body))
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
* # Page
|
* # Page
|
||||||
* ## Section1
|
* ## Section1
|
||||||
|
@@ -2,11 +2,12 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"bufio"
|
"bufio"
|
||||||
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
var nrchars, nrwords, nrlines int
|
var nrchars, nrwords, nrlines int
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
@@ -28,6 +28,7 @@ func g(i int) {
|
|||||||
fmt.Println("Printing in g", i)
|
fmt.Println("Printing in g", i)
|
||||||
g(i + 1)
|
g(i + 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
Calling g.
|
Calling g.
|
||||||
Printing in g 0
|
Printing in g 0
|
||||||
|
@@ -8,14 +8,14 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
l := int64(15000)
|
l := int64(15000)
|
||||||
if i, err := IntFromInt64(l); err!= nil {
|
if i, err := IntFromInt64(l); err != nil {
|
||||||
fmt.Printf("The conversion of %d to an int32 resulted in an error: %s", l, err.Error())
|
fmt.Printf("The conversion of %d to an int32 resulted in an error: %s", l, err.Error())
|
||||||
} else {
|
} else {
|
||||||
fmt.Printf("%d converted to an int32 is %d", l, i)
|
fmt.Printf("%d converted to an int32 is %d", l, i)
|
||||||
}
|
}
|
||||||
fmt.Println()
|
fmt.Println()
|
||||||
l = int64(math.MaxInt32 + 15000)
|
l = int64(math.MaxInt32 + 15000)
|
||||||
if i, err := IntFromInt64(l); err!= nil {
|
if i, err := IntFromInt64(l); err != nil {
|
||||||
fmt.Printf("The conversion of %d to an int32 resulted in an error: %s", l, err.Error())
|
fmt.Printf("The conversion of %d to an int32 resulted in an error: %s", l, err.Error())
|
||||||
} else {
|
} else {
|
||||||
fmt.Printf("%d converted to an int32 is %d", l, i)
|
fmt.Printf("%d converted to an int32 is %d", l, i)
|
||||||
@@ -23,21 +23,22 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ConvertInt64ToInt(l int64) int {
|
func ConvertInt64ToInt(l int64) int {
|
||||||
if math.MinInt32 <= l && l <= math.MaxInt32 {
|
if math.MinInt32 <= l && l <= math.MaxInt32 {
|
||||||
return int(l)
|
return int(l)
|
||||||
}
|
}
|
||||||
panic(fmt.Sprintf("%d is out of the int32 range", l))
|
panic(fmt.Sprintf("%d is out of the int32 range", l))
|
||||||
}
|
}
|
||||||
|
|
||||||
func IntFromInt64(l int64) (i int, err error) {
|
func IntFromInt64(l int64) (i int, err error) {
|
||||||
defer func() {
|
defer func() {
|
||||||
if e := recover(); e != nil {
|
if e := recover(); e != nil {
|
||||||
err = fmt.Errorf("%v", e)
|
err = fmt.Errorf("%v", e)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
i = ConvertInt64ToInt(l)
|
i = ConvertInt64ToInt(l)
|
||||||
return i, nil
|
return i, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
15000 converted to an int32 is 15000
|
15000 converted to an int32 is 15000
|
||||||
The conversion of 2147498647 to an int32 resulted in an error: 2147498647 is out of the int32 range
|
The conversion of 2147498647 to an int32 resulted in an error: 2147498647 is out of the int32 range
|
||||||
|
@@ -6,27 +6,28 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func badCall() {
|
func badCall() {
|
||||||
a, b := 10, 0
|
a, b := 10, 0
|
||||||
n := a / b
|
n := a / b
|
||||||
fmt.Println(n)
|
fmt.Println(n)
|
||||||
}
|
}
|
||||||
|
|
||||||
func test() {
|
func test() {
|
||||||
defer func() {
|
defer func() {
|
||||||
if e := recover(); e != nil {
|
if e := recover(); e != nil {
|
||||||
fmt.Printf("Panicing %s\r\n", e);
|
fmt.Printf("Panicing %s\r\n", e)
|
||||||
}
|
}
|
||||||
|
|
||||||
}()
|
}()
|
||||||
badCall()
|
badCall()
|
||||||
fmt.Printf("After bad call\r\n");
|
fmt.Printf("After bad call\r\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
fmt.Printf("Calling test\r\n");
|
fmt.Printf("Calling test\r\n")
|
||||||
test()
|
test()
|
||||||
fmt.Printf("Test completed\r\n");
|
fmt.Printf("Test completed\r\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
Calling test
|
Calling test
|
||||||
Panicing runtime error: integer divide by zero
|
Panicing runtime error: integer divide by zero
|
||||||
|
@@ -5,25 +5,25 @@ import "testing"
|
|||||||
import "./strev"
|
import "./strev"
|
||||||
|
|
||||||
type ReverseTest struct {
|
type ReverseTest struct {
|
||||||
in, out string
|
in, out string
|
||||||
}
|
}
|
||||||
|
|
||||||
var ReverseTests = []ReverseTest {
|
var ReverseTests = []ReverseTest{
|
||||||
ReverseTest{"ABCD", "DCBA"},
|
{"ABCD", "DCBA"},
|
||||||
ReverseTest{"CVO-AZ", "ZA-OVC"},
|
{"CVO-AZ", "ZA-OVC"},
|
||||||
ReverseTest{"Hello 世界", "界世 olleH"},
|
{"Hello 世界", "界世 olleH"},
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestReverse(t *testing.T) {
|
func TestReverse(t *testing.T) {
|
||||||
/*
|
/*
|
||||||
in := "CVO-AZ"
|
in := "CVO-AZ"
|
||||||
out := Reverse(in)
|
out := Reverse(in)
|
||||||
exp := "ZA-OVC"
|
exp := "ZA-OVC"
|
||||||
if out != exp {
|
if out != exp {
|
||||||
t.Errorf("Reverse of %s expects %s, but got %s", in, exp, out)
|
t.Errorf("Reverse of %s expects %s, but got %s", in, exp, out)
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
// testing with a battery of testdata:
|
// testing with a battery of testdata:
|
||||||
for _, r := range ReverseTests {
|
for _, r := range ReverseTests {
|
||||||
exp := strev.Reverse(r.in)
|
exp := strev.Reverse(r.in)
|
||||||
if r.out != exp {
|
if r.out != exp {
|
||||||
@@ -34,7 +34,7 @@ func TestReverse(t *testing.T) {
|
|||||||
|
|
||||||
func BenchmarkReverse(b *testing.B) {
|
func BenchmarkReverse(b *testing.B) {
|
||||||
s := "ABCD"
|
s := "ABCD"
|
||||||
for i:=0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
strev.Reverse(s)
|
strev.Reverse(s)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -14,6 +14,7 @@ func main() {
|
|||||||
c <- 10
|
c <- 10
|
||||||
fmt.Println("sent", 10)
|
fmt.Println("sent", 10)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
sending 10
|
sending 10
|
||||||
(15 s later):
|
(15 s later):
|
||||||
|
@@ -14,6 +14,7 @@ func main() {
|
|||||||
c <- 10
|
c <- 10
|
||||||
fmt.Println("sent", 10)
|
fmt.Println("sent", 10)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
sending 10
|
sending 10
|
||||||
sent 10 // prints immediately
|
sent 10 // prints immediately
|
||||||
|
@@ -39,6 +39,7 @@ func CalculatePi(n int) float64 {
|
|||||||
func term(ch chan float64, k float64) {
|
func term(ch chan float64, k float64) {
|
||||||
ch <- 4 * math.Pow(-1, k) / (2*k + 1)
|
ch <- 4 * math.Pow(-1, k) / (2*k + 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
3.14179261359579
|
3.14179261359579
|
||||||
The calculation took this amount of time: 0.028002
|
The calculation took this amount of time: 0.028002
|
||||||
|
@@ -39,6 +39,7 @@ func term(ch chan float64, start, end int) {
|
|||||||
}
|
}
|
||||||
ch <- result
|
ch <- result
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
3.1413926535917938
|
3.1413926535917938
|
||||||
The calculation took this amount of time: 0.002000
|
The calculation took this amount of time: 0.002000
|
||||||
|
@@ -18,7 +18,7 @@ func main() {
|
|||||||
fib := BuildLazyUInt64Evaluator(fibFunc, []uint64{0, 1})
|
fib := BuildLazyUInt64Evaluator(fibFunc, []uint64{0, 1})
|
||||||
|
|
||||||
for i := 0; i < 10; i++ {
|
for i := 0; i < 10; i++ {
|
||||||
fmt.Printf("Fib nr %v: %v\n", i, fib())
|
fmt.Printf("Fib nr %v: %v\n", i, fib())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,6 +45,7 @@ func BuildLazyUInt64Evaluator(evalFunc EvalFunc, initState Any) func() uint64 {
|
|||||||
return ef().(uint64)
|
return ef().(uint64)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
Fib nr 0: 0
|
Fib nr 0: 0
|
||||||
Fib nr 1: 1
|
Fib nr 1: 1
|
||||||
|
@@ -3,8 +3,8 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
|
||||||
"os"
|
"os"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
@@ -21,6 +21,7 @@ func main() {
|
|||||||
fmt.Println(i)
|
fmt.Println(i)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
1
|
1
|
||||||
1
|
1
|
||||||
|
@@ -27,6 +27,7 @@ func main() {
|
|||||||
}()
|
}()
|
||||||
fibonacci(c, quit)
|
fibonacci(c, quit)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
1
|
1
|
||||||
1
|
1
|
||||||
|
@@ -6,7 +6,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func tel(ch chan int) {
|
func tel(ch chan int) {
|
||||||
for i:=0; i < 15; i++ {
|
for i := 0; i < 15; i++ {
|
||||||
ch <- i
|
ch <- i
|
||||||
}
|
}
|
||||||
close(ch) // if this is ommitted: panic: all goroutines are asleep - deadlock!
|
close(ch) // if this is ommitted: panic: all goroutines are asleep - deadlock!
|
||||||
@@ -19,7 +19,7 @@ func main() {
|
|||||||
|
|
||||||
go tel(ch)
|
go tel(ch)
|
||||||
for ok {
|
for ok {
|
||||||
if i, ok= <-ch; ok {
|
if i, ok = <-ch; ok {
|
||||||
fmt.Printf("ok is %t and the counter is at %d\n", ok, i)
|
fmt.Printf("ok is %t and the counter is at %d\n", ok, i)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -7,7 +7,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func tel(ch chan int, quit chan bool) {
|
func tel(ch chan int, quit chan bool) {
|
||||||
for i:=0; i < 15; i++ {
|
for i := 0; i < 15; i++ {
|
||||||
ch <- i
|
ch <- i
|
||||||
}
|
}
|
||||||
quit <- true
|
quit <- true
|
||||||
@@ -21,11 +21,10 @@ func main() {
|
|||||||
go tel(ch, quit)
|
go tel(ch, quit)
|
||||||
for ok {
|
for ok {
|
||||||
select {
|
select {
|
||||||
case i:= <-ch:
|
case i := <-ch:
|
||||||
fmt.Printf("The counter is at %d\n", i)
|
fmt.Printf("The counter is at %d\n", i)
|
||||||
case <-quit:
|
case <-quit:
|
||||||
os.Exit(0)
|
os.Exit(0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -12,5 +12,5 @@ func sum(x, y int, c chan int) {
|
|||||||
func main() {
|
func main() {
|
||||||
c := make(chan int)
|
c := make(chan int)
|
||||||
go sum(12, 13, c)
|
go sum(12, 13, c)
|
||||||
fmt.Println(<-c) // 25
|
fmt.Println(<-c) // 25
|
||||||
}
|
}
|
||||||
|
@@ -26,7 +26,7 @@ func server(op binOp, service chan *Request, quit chan bool) {
|
|||||||
case req := <-service:
|
case req := <-service:
|
||||||
go run(op, req)
|
go run(op, req)
|
||||||
case <-quit:
|
case <-quit:
|
||||||
return // stop infinite loop
|
return // stop infinite loop
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -52,6 +52,7 @@ func main() {
|
|||||||
quit <- true
|
quit <- true
|
||||||
fmt.Print("done")
|
fmt.Print("done")
|
||||||
}
|
}
|
||||||
|
|
||||||
/* output:
|
/* output:
|
||||||
3+4=7 150+250=400
|
3+4=7 150+250=400
|
||||||
done
|
done
|
||||||
|
@@ -92,6 +92,7 @@ func floatsForStrings(numbers []string) ([]float64, error) {
|
|||||||
}
|
}
|
||||||
return floats, nil
|
return floats, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
Enter a radius and an angle (in degrees), e.g., 12.5 90, or Ctrl+Z, Enter to qui
|
Enter a radius and an angle (in degrees), e.g., 12.5 90, or Ctrl+Z, Enter to qui
|
||||||
t.
|
t.
|
||||||
|
@@ -28,6 +28,7 @@ func main() {
|
|||||||
|
|
||||||
<-done
|
<-done
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
0
|
0
|
||||||
10
|
10
|
||||||
|
@@ -26,4 +26,5 @@ func main() {
|
|||||||
go consume()
|
go consume()
|
||||||
<-done
|
<-done
|
||||||
}
|
}
|
||||||
|
|
||||||
// Output: 0 1 2 3 4 5 6 7 8 9
|
// Output: 0 1 2 3 4 5 6 7 8 9
|
@@ -1,10 +1,10 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"net"
|
|
||||||
"bufio"
|
"bufio"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -41,6 +41,6 @@ func main() {
|
|||||||
|
|
||||||
func checkError(error error) {
|
func checkError(error error) {
|
||||||
if error != nil {
|
if error != nil {
|
||||||
panic("Error: " + error.Error()) // terminate program
|
panic("Error: " + error.Error()) // terminate program
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -8,12 +8,13 @@ import (
|
|||||||
|
|
||||||
type Hello struct{}
|
type Hello struct{}
|
||||||
|
|
||||||
func (h Hello) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
func (h Hello) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
fmt.Fprint(w, "Hello!")
|
fmt.Fprint(w, "Hello!")
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var h Hello
|
var h Hello
|
||||||
http.ListenAndServe("localhost:4000",h)
|
http.ListenAndServe("localhost:4000", h)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Output in browser-window with url http://localhost:4000: Hello!
|
// Output in browser-window with url http://localhost:4000: Hello!
|
||||||
|
@@ -4,9 +4,9 @@ package main
|
|||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"log"
|
"log"
|
||||||
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
@@ -15,7 +15,7 @@ func main() {
|
|||||||
fmt.Print("Give the url from which to read: ")
|
fmt.Print("Give the url from which to read: ")
|
||||||
iread := bufio.NewReader(os.Stdin)
|
iread := bufio.NewReader(os.Stdin)
|
||||||
url, _ := iread.ReadString('\n')
|
url, _ := iread.ReadString('\n')
|
||||||
url = strings.Trim(url," \n\r") // trimming space,etc.
|
url = strings.Trim(url, " \n\r") // trimming space,etc.
|
||||||
// fmt.Println("***", url,"***") // debugging
|
// fmt.Println("***", url,"***") // debugging
|
||||||
res, err := http.Get(url)
|
res, err := http.Get(url)
|
||||||
CheckError(err)
|
CheckError(err)
|
||||||
|
@@ -2,8 +2,8 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
|
||||||
"net"
|
"net"
|
||||||
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -48,7 +48,7 @@ func doServerStuff(conn net.Conn) {
|
|||||||
}
|
}
|
||||||
// extract clientname:
|
// extract clientname:
|
||||||
ix := strings.Index(input, "says")
|
ix := strings.Index(input, "says")
|
||||||
clName := input[0:ix-1]
|
clName := input[0 : ix-1]
|
||||||
//fmt.Printf("The clientname is ---%s---\n", string(clName))
|
//fmt.Printf("The clientname is ---%s---\n", string(clName))
|
||||||
// set clientname active in mapUsers:
|
// set clientname active in mapUsers:
|
||||||
mapUsers[string(clName)] = 1
|
mapUsers[string(clName)] = 1
|
||||||
@@ -61,7 +61,7 @@ func doServerStuff(conn net.Conn) {
|
|||||||
// a simple return continues in the function where we came from!
|
// a simple return continues in the function where we came from!
|
||||||
func checkError(error error) {
|
func checkError(error error) {
|
||||||
if error != nil {
|
if error != nil {
|
||||||
panic("Error: " + error.Error()) // terminate program
|
panic("Error: " + error.Error()) // terminate program
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -3,11 +3,11 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"log"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
type statistics struct {
|
type statistics struct {
|
||||||
@@ -16,7 +16,7 @@ type statistics struct {
|
|||||||
median float64
|
median float64
|
||||||
}
|
}
|
||||||
|
|
||||||
const form = `<html><body><form action="/" method="POST">
|
const form = `<html><body><form action="/" method="POST">
|
||||||
<label for="numbers">Numbers (comma or space-separated):</label><br>
|
<label for="numbers">Numbers (comma or space-separated):</label><br>
|
||||||
<input type="text" name="numbers" size="30"><br />
|
<input type="text" name="numbers" size="30"><br />
|
||||||
<input type="submit" value="Calculate">
|
<input type="submit" value="Calculate">
|
||||||
@@ -29,50 +29,50 @@ var pageBottom = ""
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
http.HandleFunc("/", homePage)
|
http.HandleFunc("/", homePage)
|
||||||
if err := http.ListenAndServe(":9001", nil); err != nil {
|
if err := http.ListenAndServe(":9001", nil); err != nil {
|
||||||
log.Fatal("failed to start server", err)
|
log.Fatal("failed to start server", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func homePage(writer http.ResponseWriter, request *http.Request) {
|
func homePage(writer http.ResponseWriter, request *http.Request) {
|
||||||
writer.Header().Set("Content-Type", "text/html")
|
writer.Header().Set("Content-Type", "text/html")
|
||||||
err := request.ParseForm() // Must be called before writing response
|
err := request.ParseForm() // Must be called before writing response
|
||||||
fmt.Fprint(writer, pageTop, form)
|
fmt.Fprint(writer, pageTop, form)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(writer, error, err)
|
fmt.Fprintf(writer, error, err)
|
||||||
} else {
|
} else {
|
||||||
if numbers, message, ok := processRequest(request); ok {
|
if numbers, message, ok := processRequest(request); ok {
|
||||||
stats := getStats(numbers)
|
stats := getStats(numbers)
|
||||||
fmt.Fprint(writer, formatStats(stats))
|
fmt.Fprint(writer, formatStats(stats))
|
||||||
} else if message != "" {
|
} else if message != "" {
|
||||||
fmt.Fprintf(writer, error, message)
|
fmt.Fprintf(writer, error, message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fmt.Fprint(writer, pageBottom)
|
fmt.Fprint(writer, pageBottom)
|
||||||
}
|
}
|
||||||
|
|
||||||
func processRequest(request *http.Request) ([]float64, string, bool) {
|
func processRequest(request *http.Request) ([]float64, string, bool) {
|
||||||
var numbers []float64
|
var numbers []float64
|
||||||
var text string
|
var text string
|
||||||
if slice, found := request.Form["numbers"]; found && len(slice) > 0 {
|
if slice, found := request.Form["numbers"]; found && len(slice) > 0 {
|
||||||
//处理如果网页中输入的是中文逗号
|
//处理如果网页中输入的是中文逗号
|
||||||
if strings.Contains(slice[0], ",") {
|
if strings.Contains(slice[0], ",") {
|
||||||
text = strings.Replace(slice[0], ",", " ", -1)
|
text = strings.Replace(slice[0], ",", " ", -1)
|
||||||
} else {
|
} else {
|
||||||
text = strings.Replace(slice[0], ",", " ", -1)
|
text = strings.Replace(slice[0], ",", " ", -1)
|
||||||
|
}
|
||||||
|
for _, field := range strings.Fields(text) {
|
||||||
|
if x, err := strconv.ParseFloat(field, 64); err != nil {
|
||||||
|
return numbers, "'" + field + "' is invalid", false
|
||||||
|
} else {
|
||||||
|
numbers = append(numbers, x)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
for _, field := range strings.Fields(text) {
|
if len(numbers) == 0 {
|
||||||
if x, err := strconv.ParseFloat(field, 64); err != nil {
|
return numbers, "", false // no data first time form is shown
|
||||||
return numbers, "'" + field + "' is invalid", false
|
}
|
||||||
} else {
|
return numbers, "", true
|
||||||
numbers = append(numbers, x)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(numbers) == 0 {
|
|
||||||
return numbers, "", false // no data first time form is shown
|
|
||||||
}
|
|
||||||
return numbers, "", true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func getStats(numbers []float64) (stats statistics) {
|
func getStats(numbers []float64) (stats statistics) {
|
||||||
@@ -91,7 +91,7 @@ func sum(numbers []float64) (total float64) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func median(numbers []float64) float64 {
|
func median(numbers []float64) float64 {
|
||||||
middle := len(numbers)/2
|
middle := len(numbers) / 2
|
||||||
result := numbers[middle]
|
result := numbers[middle]
|
||||||
if len(numbers)%2 == 0 {
|
if len(numbers)%2 == 0 {
|
||||||
result = (result + numbers[middle-1]) / 2
|
result = (result + numbers[middle-1]) / 2
|
||||||
@@ -100,7 +100,7 @@ func median(numbers []float64) float64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func formatStats(stats statistics) string {
|
func formatStats(stats statistics) string {
|
||||||
return fmt.Sprintf(`<table border="1">
|
return fmt.Sprintf(`<table border="1">
|
||||||
<tr><th colspan="2">Results</th></tr>
|
<tr><th colspan="2">Results</th></tr>
|
||||||
<tr><td>Numbers</td><td>%v</td></tr>
|
<tr><td>Numbers</td><td>%v</td></tr>
|
||||||
<tr><td>Count</td><td>%d</td></tr>
|
<tr><td>Count</td><td>%d</td></tr>
|
||||||
|
@@ -2,9 +2,9 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"text/template"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
"text/template"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -22,6 +22,7 @@ func main() {
|
|||||||
fmt.Println("The next one ought to fail.")
|
fmt.Println("The next one ought to fail.")
|
||||||
template.Must(tErr.Parse(" some static text {{ .Name }"))
|
template.Must(tErr.Parse(" some static text {{ .Name }"))
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
The first one parsed OK.
|
The first one parsed OK.
|
||||||
The next one ought to fail.
|
The next one ought to fail.
|
||||||
|
@@ -2,31 +2,32 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"encoding/json"
|
"io/ioutil"
|
||||||
"io/ioutil"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Status struct {
|
type Status struct {
|
||||||
Text string
|
Text string
|
||||||
}
|
}
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
Status Status
|
Status Status
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
/* perform an HTTP request for the twitter status of user: Googland */
|
/* perform an HTTP request for the twitter status of user: Googland */
|
||||||
res, _:= http.Get("http://twitter.com/users/Googland.json")
|
res, _ := http.Get("http://twitter.com/users/Googland.json")
|
||||||
/* initialize the structure of the JSON response */
|
/* initialize the structure of the JSON response */
|
||||||
user := User{Status{""}}
|
user := User{Status{""}}
|
||||||
/* unmarshal the JSON into our structures */
|
/* unmarshal the JSON into our structures */
|
||||||
temp, _ := ioutil.ReadAll(res.Body)
|
temp, _ := ioutil.ReadAll(res.Body)
|
||||||
body := []byte(temp)
|
body := []byte(temp)
|
||||||
json.Unmarshal(body, &user)
|
json.Unmarshal(body, &user)
|
||||||
fmt.Printf("status: %s", user.Status.Text)
|
fmt.Printf("status: %s", user.Status.Text)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Output:
|
/* Output:
|
||||||
status: Robot cars invade California, on orders from Google:
|
status: Robot cars invade California, on orders from Google:
|
||||||
Google has been testing self-driving cars ... http://bit.ly/cbtpUN http://retwt.me/97p
|
Google has been testing self-driving cars ... http://bit.ly/cbtpUN http://retwt.me/97p
|
||||||
|
@@ -2,23 +2,23 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"fmt"
|
||||||
"fmt"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func helloHandler(w http.ResponseWriter, r *http.Request) {
|
func helloHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
remPartOfURL := r.URL.Path[len("/hello/"):] //get everything after the /hello/ part of the URL
|
remPartOfURL := r.URL.Path[len("/hello/"):] //get everything after the /hello/ part of the URL
|
||||||
fmt.Fprintf(w, "Hello %s!", remPartOfURL)
|
fmt.Fprintf(w, "Hello %s!", remPartOfURL)
|
||||||
}
|
}
|
||||||
|
|
||||||
func shouthelloHandler(w http.ResponseWriter, r *http.Request) {
|
func shouthelloHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
remPartOfURL := r.URL.Path[len("/shouthello/"):] //get everything after the /shouthello/ part of the URL
|
remPartOfURL := r.URL.Path[len("/shouthello/"):] //get everything after the /shouthello/ part of the URL
|
||||||
fmt.Fprintf(w, "Hello %s!", strings.ToUpper(remPartOfURL))
|
fmt.Fprintf(w, "Hello %s!", strings.ToUpper(remPartOfURL))
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
http.HandleFunc("/hello/", helloHandler)
|
http.HandleFunc("/hello/", helloHandler)
|
||||||
http.HandleFunc("/shouthello/", shouthelloHandler)
|
http.HandleFunc("/shouthello/", shouthelloHandler)
|
||||||
http.ListenAndServe("localhost:9999", nil)
|
http.ListenAndServe("localhost:9999", nil)
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user