All previous code added
This commit is contained in:
parent
a39cfd0b05
commit
dd11dda7bd
134 changed files with 6395 additions and 0 deletions
61
ch05/binTree.go
Normal file
61
ch05/binTree.go
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Tree struct {
|
||||
Left *Tree
|
||||
Value int
|
||||
Right *Tree
|
||||
}
|
||||
|
||||
func traverse(t *Tree) {
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
traverse(t.Left)
|
||||
fmt.Print(t.Value, " ")
|
||||
traverse(t.Right)
|
||||
}
|
||||
|
||||
func create(n int) *Tree {
|
||||
var t *Tree
|
||||
rand.Seed(time.Now().Unix())
|
||||
for i := 0; i < 2*n; i++ {
|
||||
temp := rand.Intn(n * 2)
|
||||
t = insert(t, temp)
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func insert(t *Tree, v int) *Tree {
|
||||
if t == nil {
|
||||
return &Tree{nil, v, nil}
|
||||
}
|
||||
|
||||
if v == t.Value {
|
||||
return t
|
||||
}
|
||||
|
||||
if v < t.Value {
|
||||
t.Left = insert(t.Left, v)
|
||||
return t
|
||||
}
|
||||
t.Right = insert(t.Right, v)
|
||||
return t
|
||||
}
|
||||
|
||||
func main() {
|
||||
tree := create(10)
|
||||
fmt.Println("The value of the root of the tree is", tree.Value)
|
||||
traverse(tree)
|
||||
fmt.Println()
|
||||
tree = insert(tree, -10)
|
||||
tree = insert(tree, -2)
|
||||
traverse(tree)
|
||||
fmt.Println()
|
||||
fmt.Println("The value of the root of the tree is", tree.Value)
|
||||
}
|
||||
46
ch05/conHeap.go
Normal file
46
ch05/conHeap.go
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type heapFloat32 []float32
|
||||
|
||||
func (n *heapFloat32) Pop() interface{} {
|
||||
old := *n
|
||||
x := old[len(old)-1]
|
||||
new := old[0 : len(old)-1]
|
||||
*n = new
|
||||
return x
|
||||
}
|
||||
|
||||
func (n *heapFloat32) Push(x interface{}) {
|
||||
*n = append(*n, x.(float32))
|
||||
}
|
||||
|
||||
func (n heapFloat32) Len() int {
|
||||
return len(n)
|
||||
}
|
||||
|
||||
func (n heapFloat32) Less(a, b int) bool {
|
||||
return n[a] < n[b]
|
||||
}
|
||||
|
||||
func (n heapFloat32) Swap(a, b int) {
|
||||
n[a], n[b] = n[b], n[a]
|
||||
}
|
||||
|
||||
func main() {
|
||||
myHeap := &heapFloat32{1.2, 2.1, 3.1, -100.1}
|
||||
heap.Init(myHeap)
|
||||
size := len(*myHeap)
|
||||
fmt.Printf("Heap size: %d\n", size)
|
||||
fmt.Printf("%v\n", myHeap)
|
||||
myHeap.Push(float32(-100.2))
|
||||
myHeap.Push(float32(0.2))
|
||||
fmt.Printf("Heap size: %d\n", len(*myHeap))
|
||||
fmt.Printf("%v\n", myHeap)
|
||||
heap.Init(myHeap)
|
||||
fmt.Printf("%v\n", myHeap)
|
||||
}
|
||||
46
ch05/conList.go
Normal file
46
ch05/conList.go
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func printList(l *list.List) {
|
||||
for t := l.Back(); t != nil; t = t.Prev() {
|
||||
fmt.Print(t.Value, " ")
|
||||
}
|
||||
fmt.Println()
|
||||
|
||||
for t := l.Front(); t != nil; t = t.Next() {
|
||||
fmt.Print(t.Value, " ")
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
values := list.New()
|
||||
|
||||
e1 := values.PushBack("One")
|
||||
e2 := values.PushBack("Two")
|
||||
values.PushFront("Three")
|
||||
values.InsertBefore("Four", e1)
|
||||
values.InsertAfter("Five", e2)
|
||||
values.Remove(e2)
|
||||
values.Remove(e2)
|
||||
values.InsertAfter("FiveFive", e2)
|
||||
values.PushBackList(values)
|
||||
|
||||
printList(values)
|
||||
|
||||
values.Init()
|
||||
fmt.Printf("After Init(): %v\n", values)
|
||||
|
||||
for i := 0; i < 20; i++ {
|
||||
values.PushFront(strconv.Itoa(i))
|
||||
}
|
||||
|
||||
printList(values)
|
||||
}
|
||||
33
ch05/conRing.go
Normal file
33
ch05/conRing.go
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"container/ring"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var size int = 10
|
||||
|
||||
func main() {
|
||||
myRing := ring.New(size + 1)
|
||||
fmt.Println("Empty ring:", *myRing)
|
||||
|
||||
for i := 0; i < myRing.Len()-1; i++ {
|
||||
myRing.Value = i
|
||||
myRing = myRing.Next()
|
||||
}
|
||||
|
||||
myRing.Value = 2
|
||||
|
||||
sum := 0
|
||||
myRing.Do(func(x interface{}) {
|
||||
t := x.(int)
|
||||
sum = sum + t
|
||||
})
|
||||
fmt.Println("Sum:", sum)
|
||||
|
||||
for i := 0; i < myRing.Len()+2; i++ {
|
||||
myRing = myRing.Next()
|
||||
fmt.Print(myRing.Value, " ")
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
115
ch05/doublyLList.go
Normal file
115
ch05/doublyLList.go
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Node struct {
|
||||
Value int
|
||||
Previous *Node
|
||||
Next *Node
|
||||
}
|
||||
|
||||
func addNode(t *Node, v int) int {
|
||||
if root == nil {
|
||||
t = &Node{v, nil, nil}
|
||||
root = t
|
||||
return 0
|
||||
}
|
||||
|
||||
if v == t.Value {
|
||||
fmt.Println("Node already exists:", v)
|
||||
return -1
|
||||
}
|
||||
|
||||
if t.Next == nil {
|
||||
temp := t
|
||||
t.Next = &Node{v, temp, nil}
|
||||
return -2
|
||||
}
|
||||
|
||||
return addNode(t.Next, v)
|
||||
}
|
||||
|
||||
func traverse(t *Node) {
|
||||
if t == nil {
|
||||
fmt.Println("-> Empty list!")
|
||||
return
|
||||
}
|
||||
|
||||
for t != nil {
|
||||
fmt.Printf("%d -> ", t.Value)
|
||||
t = t.Next
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
func reverse(t *Node) {
|
||||
if t == nil {
|
||||
fmt.Println("-> Empty list!")
|
||||
return
|
||||
}
|
||||
|
||||
temp := t
|
||||
for t != nil {
|
||||
temp = t
|
||||
t = t.Next
|
||||
}
|
||||
|
||||
for temp.Previous != nil {
|
||||
fmt.Printf("%d -> ", temp.Value)
|
||||
temp = temp.Previous
|
||||
}
|
||||
fmt.Printf("%d -> ", temp.Value)
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
func size(t *Node) int {
|
||||
if t == nil {
|
||||
fmt.Println("-> Empty list!")
|
||||
return 0
|
||||
}
|
||||
|
||||
n := 0
|
||||
for t != nil {
|
||||
n++
|
||||
t = t.Next
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func lookupNode(t *Node, v int) bool {
|
||||
if root == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if v == t.Value {
|
||||
return true
|
||||
}
|
||||
|
||||
if t.Next == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return lookupNode(t.Next, v)
|
||||
}
|
||||
|
||||
var root = new(Node)
|
||||
|
||||
func main() {
|
||||
fmt.Println(root)
|
||||
root = nil
|
||||
traverse(root)
|
||||
addNode(root, 1)
|
||||
addNode(root, 1)
|
||||
traverse(root)
|
||||
addNode(root, 10)
|
||||
addNode(root, 5)
|
||||
addNode(root, 0)
|
||||
addNode(root, 0)
|
||||
traverse(root)
|
||||
addNode(root, 100)
|
||||
fmt.Println("Size:", size(root))
|
||||
traverse(root)
|
||||
reverse(root)
|
||||
}
|
||||
43
ch05/generatePassword.go
Normal file
43
ch05/generatePassword.go
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func random(min, max int) int {
|
||||
return rand.Intn(max-min) + min
|
||||
}
|
||||
|
||||
func main() {
|
||||
MIN := 0
|
||||
MAX := 94
|
||||
SEED := time.Now().Unix()
|
||||
var LENGTH int64 = 8
|
||||
|
||||
arguments := os.Args
|
||||
switch len(arguments) {
|
||||
case 2:
|
||||
LENGTH, _ = strconv.ParseInt(os.Args[1], 10, 64)
|
||||
default:
|
||||
fmt.Println("Using default values!")
|
||||
}
|
||||
|
||||
rand.Seed(SEED)
|
||||
|
||||
startChar := "!"
|
||||
var i int64 = 1
|
||||
for {
|
||||
myRand := random(MIN, MAX)
|
||||
newChar := string(startChar[0] + byte(myRand))
|
||||
fmt.Print(newChar)
|
||||
if i == LENGTH {
|
||||
break
|
||||
}
|
||||
i++
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
51
ch05/hashTable.go
Normal file
51
ch05/hashTable.go
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const SIZE = 15
|
||||
|
||||
type Node struct {
|
||||
Value int
|
||||
Next *Node
|
||||
}
|
||||
|
||||
type HashTable struct {
|
||||
Table map[int]*Node
|
||||
Size int
|
||||
}
|
||||
|
||||
func hashFunction(i, size int) int {
|
||||
return (i % size)
|
||||
}
|
||||
|
||||
func insert(hash *HashTable, value int) int {
|
||||
index := hashFunction(value, hash.Size)
|
||||
element := Node{Value: value, Next: hash.Table[index]}
|
||||
hash.Table[index] = &element
|
||||
return index
|
||||
}
|
||||
|
||||
func traverse(hash *HashTable) {
|
||||
for k := range hash.Table {
|
||||
if hash.Table[k] != nil {
|
||||
t := hash.Table[k]
|
||||
for t != nil {
|
||||
fmt.Printf("%d -> ", t.Value)
|
||||
t = t.Next
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
table := make(map[int]*Node, SIZE)
|
||||
hash := &HashTable{Table: table, Size: SIZE}
|
||||
fmt.Println("Number of spaces:", hash.Size)
|
||||
for i := 0; i < 120; i++ {
|
||||
insert(hash, i)
|
||||
}
|
||||
traverse(hash)
|
||||
}
|
||||
69
ch05/hashTableLookup.go
Normal file
69
ch05/hashTableLookup.go
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const SIZE = 15
|
||||
|
||||
type Node struct {
|
||||
Value int
|
||||
Next *Node
|
||||
}
|
||||
|
||||
type HashTable struct {
|
||||
Table map[int]*Node
|
||||
Size int
|
||||
}
|
||||
|
||||
func hashFunction(i, size int) int {
|
||||
return (i % size)
|
||||
}
|
||||
|
||||
func insert(hash *HashTable, value int) int {
|
||||
index := hashFunction(value, hash.Size)
|
||||
element := Node{Value: value, Next: hash.Table[index]}
|
||||
hash.Table[index] = &element
|
||||
return index
|
||||
}
|
||||
|
||||
func traverse(hash *HashTable) {
|
||||
for k := range hash.Table {
|
||||
if hash.Table[k] != nil {
|
||||
t := hash.Table[k]
|
||||
for t != nil {
|
||||
fmt.Printf("%d -> ", t.Value)
|
||||
t = t.Next
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func lookup(hash *HashTable, value int) bool {
|
||||
index := hashFunction(value, hash.Size)
|
||||
if hash.Table[index] != nil {
|
||||
t := hash.Table[index]
|
||||
for t != nil {
|
||||
if t.Value == value {
|
||||
return true
|
||||
}
|
||||
t = t.Next
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func main() {
|
||||
table := make(map[int]*Node, SIZE)
|
||||
hash := &HashTable{Table: table, Size: SIZE}
|
||||
for i := 0; i < 120; i++ {
|
||||
insert(hash, i)
|
||||
}
|
||||
|
||||
for i := 10; i < 125; i++ {
|
||||
if !lookup(hash, i) {
|
||||
fmt.Println(i, "is not in the hash table!")
|
||||
}
|
||||
}
|
||||
}
|
||||
106
ch05/linkedList.go
Normal file
106
ch05/linkedList.go
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Node struct {
|
||||
Value int
|
||||
Next *Node
|
||||
}
|
||||
|
||||
var root = new(Node)
|
||||
|
||||
func addNode(t *Node, v int) int {
|
||||
if root == nil {
|
||||
t = &Node{v, nil}
|
||||
root = t
|
||||
return 0
|
||||
}
|
||||
|
||||
if v == t.Value {
|
||||
fmt.Println("Node already exists:", v)
|
||||
return -1
|
||||
}
|
||||
|
||||
if t.Next == nil {
|
||||
t.Next = &Node{v, nil}
|
||||
return -2
|
||||
}
|
||||
|
||||
return addNode(t.Next, v)
|
||||
}
|
||||
|
||||
func traverse(t *Node) {
|
||||
if t == nil {
|
||||
fmt.Println("-> Empty list!")
|
||||
return
|
||||
}
|
||||
|
||||
for t != nil {
|
||||
fmt.Printf("%d -> ", t.Value)
|
||||
t = t.Next
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
func lookupNode(t *Node, v int) bool {
|
||||
if root == nil {
|
||||
t = &Node{v, nil}
|
||||
root = t
|
||||
return false
|
||||
}
|
||||
|
||||
if v == t.Value {
|
||||
return true
|
||||
}
|
||||
|
||||
if t.Next == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return lookupNode(t.Next, v)
|
||||
}
|
||||
|
||||
func size(t *Node) int {
|
||||
if t == nil {
|
||||
fmt.Println("-> Empty list!")
|
||||
return 0
|
||||
}
|
||||
|
||||
i := 0
|
||||
for t != nil {
|
||||
i++
|
||||
t = t.Next
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println(root)
|
||||
root = nil
|
||||
traverse(root)
|
||||
addNode(root, 1)
|
||||
addNode(root, -1)
|
||||
traverse(root)
|
||||
addNode(root, 10)
|
||||
addNode(root, 5)
|
||||
addNode(root, 45)
|
||||
addNode(root, 5)
|
||||
addNode(root, 5)
|
||||
traverse(root)
|
||||
addNode(root, 100)
|
||||
traverse(root)
|
||||
|
||||
if lookupNode(root, 100) {
|
||||
fmt.Println("Node exists!")
|
||||
} else {
|
||||
fmt.Println("Node does not exist!")
|
||||
}
|
||||
|
||||
if lookupNode(root, -100) {
|
||||
fmt.Println("Node exists!")
|
||||
} else {
|
||||
fmt.Println("Node does not exist!")
|
||||
}
|
||||
}
|
||||
97
ch05/queue.go
Normal file
97
ch05/queue.go
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Node struct {
|
||||
Value int
|
||||
Next *Node
|
||||
}
|
||||
|
||||
var size = 0
|
||||
var queue = new(Node)
|
||||
|
||||
func Push(t *Node, v int) bool {
|
||||
if queue == nil {
|
||||
queue = &Node{v, nil}
|
||||
size++
|
||||
return true
|
||||
}
|
||||
|
||||
t = &Node{v, nil}
|
||||
t.Next = queue
|
||||
queue = t
|
||||
size++
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func Pop(t *Node) (int, bool) {
|
||||
if size == 0 {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
if size == 1 {
|
||||
queue = nil
|
||||
size--
|
||||
return t.Value, true
|
||||
}
|
||||
|
||||
temp := t
|
||||
for (t.Next) != nil {
|
||||
temp = t
|
||||
t = t.Next
|
||||
}
|
||||
|
||||
v := (temp.Next).Value
|
||||
temp.Next = nil
|
||||
|
||||
size--
|
||||
return v, true
|
||||
}
|
||||
|
||||
func traverse(t *Node) {
|
||||
if size == 0 {
|
||||
fmt.Println("Empty Queue!")
|
||||
return
|
||||
}
|
||||
|
||||
for t != nil {
|
||||
fmt.Printf("%d -> ", t.Value)
|
||||
t = t.Next
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
func main() {
|
||||
queue = nil
|
||||
Push(queue, 10)
|
||||
fmt.Println("Size:", size)
|
||||
traverse(queue)
|
||||
|
||||
v, b := Pop(queue)
|
||||
if b {
|
||||
fmt.Println("Pop:", v)
|
||||
}
|
||||
fmt.Println("Size:", size)
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
Push(queue, i)
|
||||
}
|
||||
traverse(queue)
|
||||
fmt.Println("Size:", size)
|
||||
|
||||
v, b = Pop(queue)
|
||||
if b {
|
||||
fmt.Println("Pop:", v)
|
||||
}
|
||||
fmt.Println("Size:", size)
|
||||
|
||||
v, b = Pop(queue)
|
||||
if b {
|
||||
fmt.Println("Pop:", v)
|
||||
}
|
||||
fmt.Println("Size:", size)
|
||||
traverse(queue)
|
||||
}
|
||||
52
ch05/randomNumbers.go
Normal file
52
ch05/randomNumbers.go
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func random(min, max int) int {
|
||||
return rand.Intn(max-min) + min
|
||||
}
|
||||
|
||||
func main() {
|
||||
MIN := 0
|
||||
MAX := 100
|
||||
TOTAL := 100
|
||||
SEED := time.Now().Unix()
|
||||
|
||||
arguments := os.Args
|
||||
switch len(arguments) {
|
||||
case 2:
|
||||
fmt.Println("Usage: ./randomNumbers MIN MAX TOTAL SEED")
|
||||
MIN, _ = strconv.Atoi(arguments[1])
|
||||
MAX = MIN + 100
|
||||
case 3:
|
||||
fmt.Println("Usage: ./randomNumbers MIN MAX TOTAL SEED")
|
||||
MIN, _ = strconv.Atoi(arguments[1])
|
||||
MAX, _ = strconv.Atoi(arguments[2])
|
||||
case 4:
|
||||
fmt.Println("Usage: ./randomNumbers MIN MAX TOTAL SEED")
|
||||
MIN, _ = strconv.Atoi(arguments[1])
|
||||
MAX, _ = strconv.Atoi(arguments[2])
|
||||
TOTAL, _ = strconv.Atoi(arguments[3])
|
||||
case 5:
|
||||
MIN, _ = strconv.Atoi(arguments[1])
|
||||
MAX, _ = strconv.Atoi(arguments[2])
|
||||
TOTAL, _ = strconv.Atoi(arguments[3])
|
||||
SEED, _ = strconv.ParseInt(arguments[4], 10, 64)
|
||||
default:
|
||||
fmt.Println("Using default values!")
|
||||
}
|
||||
|
||||
rand.Seed(SEED)
|
||||
for i := 0; i < TOTAL; i++ {
|
||||
myrand := random(MIN, MAX)
|
||||
fmt.Print(myrand)
|
||||
fmt.Print(" ")
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
87
ch05/stack.go
Normal file
87
ch05/stack.go
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Node struct {
|
||||
Value int
|
||||
Next *Node
|
||||
}
|
||||
|
||||
var size = 0
|
||||
var stack = new(Node)
|
||||
|
||||
func Push(v int) bool {
|
||||
if stack == nil {
|
||||
stack = &Node{v, nil}
|
||||
size = 1
|
||||
return true
|
||||
}
|
||||
|
||||
temp := &Node{v, nil}
|
||||
temp.Next = stack
|
||||
stack = temp
|
||||
size++
|
||||
return true
|
||||
}
|
||||
|
||||
func Pop(t *Node) (int, bool) {
|
||||
if size == 0 {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
if size == 1 {
|
||||
size = 0
|
||||
stack = nil
|
||||
return t.Value, true
|
||||
}
|
||||
|
||||
stack = stack.Next
|
||||
size--
|
||||
return t.Value, true
|
||||
}
|
||||
|
||||
func traverse(t *Node) {
|
||||
if size == 0 {
|
||||
fmt.Println("Empty Stack!")
|
||||
return
|
||||
}
|
||||
|
||||
for t != nil {
|
||||
fmt.Printf("%d -> ", t.Value)
|
||||
t = t.Next
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
stack = nil
|
||||
v, b := Pop(stack)
|
||||
if b {
|
||||
fmt.Print(v, " ")
|
||||
} else {
|
||||
fmt.Println("Pop() failed!")
|
||||
}
|
||||
|
||||
Push(100)
|
||||
traverse(stack)
|
||||
Push(200)
|
||||
traverse(stack)
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
Push(i)
|
||||
}
|
||||
|
||||
for i := 0; i < 15; i++ {
|
||||
v, b := Pop(stack)
|
||||
if b {
|
||||
fmt.Print(v, " ")
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
fmt.Println()
|
||||
traverse(stack)
|
||||
}
|
||||
13
ch06/a.go
Normal file
13
ch06/a.go
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
package a
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func init() {
|
||||
fmt.Println("init() a")
|
||||
}
|
||||
|
||||
func FromA() {
|
||||
fmt.Println("fromA()")
|
||||
}
|
||||
16
ch06/aPackage.go
Normal file
16
ch06/aPackage.go
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
package aPackage
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func A() {
|
||||
fmt.Println("This is function A!")
|
||||
}
|
||||
|
||||
func B() {
|
||||
fmt.Println("privateConstant:", privateConstant)
|
||||
}
|
||||
|
||||
const MyConstant = 123
|
||||
const privateConstant = 21
|
||||
15
ch06/b.go
Normal file
15
ch06/b.go
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
package b
|
||||
|
||||
import (
|
||||
"a"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func init() {
|
||||
fmt.Println("init() b")
|
||||
}
|
||||
|
||||
func FromB() {
|
||||
fmt.Println("fromB()")
|
||||
a.FromA()
|
||||
}
|
||||
21
ch06/funFun.go
Normal file
21
ch06/funFun.go
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func function1(i int) int {
|
||||
return i + i
|
||||
}
|
||||
|
||||
func function2(i int) int {
|
||||
return i * i
|
||||
}
|
||||
|
||||
func funFun(f func(int) int, v int) int {
|
||||
return f(v)
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println("function1:", funFun(function1, 123))
|
||||
fmt.Println("function2:", funFun(function2, 123))
|
||||
fmt.Println("Inline", funFun(func(i int) int { return i * i * i }, 123))
|
||||
}
|
||||
39
ch06/functions.go
Normal file
39
ch06/functions.go
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func doubleSquare(x int) (int, int) {
|
||||
return x * 2, x * x
|
||||
}
|
||||
|
||||
func main() {
|
||||
arguments := os.Args
|
||||
if len(arguments) != 2 {
|
||||
fmt.Println("The program needs 1 argument!")
|
||||
return
|
||||
}
|
||||
|
||||
y, err := strconv.Atoi(arguments[1])
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
square := func(s int) int {
|
||||
return s * s
|
||||
}
|
||||
fmt.Println("The square of", y, "is", square(y))
|
||||
|
||||
double := func(s int) int {
|
||||
return s + s
|
||||
}
|
||||
fmt.Println("The double of", y, "is", double(y))
|
||||
|
||||
fmt.Println(doubleSquare(y))
|
||||
d, s := doubleSquare(y)
|
||||
fmt.Println(d, s)
|
||||
}
|
||||
38
ch06/html.gohtml
Normal file
38
ch06/html.gohtml
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Doing Maths in Go!</title>
|
||||
<style>
|
||||
html {
|
||||
font-size: 14px;
|
||||
}
|
||||
table, th, td {
|
||||
border: 2px solid blue;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Number</th>
|
||||
<th>Double</th>
|
||||
<th>Square</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{{ range . }}
|
||||
<tr>
|
||||
<td> {{ .Number }} </td>
|
||||
<td> {{ .Double }} </td>
|
||||
<td> {{ .Square }} </td>
|
||||
</tr>
|
||||
{{ end }}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
BIN
ch06/htmlT.db
Normal file
BIN
ch06/htmlT.db
Normal file
Binary file not shown.
77
ch06/htmlT.go
Normal file
77
ch06/htmlT.go
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
type Entry struct {
|
||||
Number int
|
||||
Double int
|
||||
Square int
|
||||
}
|
||||
|
||||
var DATA []Entry
|
||||
var tFile string
|
||||
|
||||
func myHandler(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Printf("Host: %s Path: %s\n", r.Host, r.URL.Path)
|
||||
myT := template.Must(template.ParseGlob(tFile))
|
||||
myT.ExecuteTemplate(w, tFile, DATA)
|
||||
}
|
||||
|
||||
func main() {
|
||||
arguments := os.Args
|
||||
if len(arguments) != 3 {
|
||||
fmt.Println("Need Database File + Template File!")
|
||||
return
|
||||
}
|
||||
|
||||
database := arguments[1]
|
||||
tFile = arguments[2]
|
||||
|
||||
db, err := sql.Open("sqlite3", database)
|
||||
if err != nil {
|
||||
fmt.Println(nil)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("Emptying database table.")
|
||||
_, err = db.Exec("DELETE FROM data")
|
||||
if err != nil {
|
||||
fmt.Println(nil)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("Populating", database)
|
||||
stmt, _ := db.Prepare("INSERT INTO data(number, double, square) values(?,?,?)")
|
||||
for i := 20; i < 50; i++ {
|
||||
_, _ = stmt.Exec(i, 2*i, i*i)
|
||||
}
|
||||
|
||||
rows, err := db.Query("SELECT * FROM data")
|
||||
if err != nil {
|
||||
fmt.Println(nil)
|
||||
return
|
||||
}
|
||||
|
||||
var n int
|
||||
var d int
|
||||
var s int
|
||||
for rows.Next() {
|
||||
err = rows.Scan(&n, &d, &s)
|
||||
temp := Entry{Number: n, Double: d, Square: s}
|
||||
DATA = append(DATA, temp)
|
||||
}
|
||||
|
||||
http.HandleFunc("/", myHandler)
|
||||
err = http.ListenAndServe(":8080", nil)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
16
ch06/manyInit.go
Normal file
16
ch06/manyInit.go
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"a"
|
||||
"b"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func init() {
|
||||
fmt.Println("init() manyInit")
|
||||
}
|
||||
|
||||
func main() {
|
||||
a.FromA()
|
||||
b.FromB()
|
||||
}
|
||||
16
ch06/ptrFun.go
Normal file
16
ch06/ptrFun.go
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func getPtr(v *float64) float64 {
|
||||
return *v * *v
|
||||
}
|
||||
|
||||
func main() {
|
||||
x := 12.2
|
||||
fmt.Println(getPtr(&x))
|
||||
x = 12
|
||||
fmt.Println(getPtr(&x))
|
||||
}
|
||||
24
ch06/returnFunction.go
Normal file
24
ch06/returnFunction.go
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func funReturnFun() func() int {
|
||||
i := 0
|
||||
return func() int {
|
||||
i++
|
||||
return i * i
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
i := funReturnFun()
|
||||
j := funReturnFun()
|
||||
|
||||
fmt.Println("1:", i())
|
||||
fmt.Println("2:", i())
|
||||
fmt.Println("j1:", j())
|
||||
fmt.Println("j2:", j())
|
||||
fmt.Println("3:", i())
|
||||
}
|
||||
48
ch06/returnNames.go
Normal file
48
ch06/returnNames.go
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func namedMinMax(x, y int) (min, max int) {
|
||||
if x > y {
|
||||
min = y
|
||||
max = x
|
||||
} else {
|
||||
min = x
|
||||
max = y
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func minMax(x, y int) (min, max int) {
|
||||
if x > y {
|
||||
min = y
|
||||
max = x
|
||||
} else {
|
||||
min = x
|
||||
max = y
|
||||
}
|
||||
return min, max
|
||||
}
|
||||
|
||||
func main() {
|
||||
arguments := os.Args
|
||||
if len(arguments) < 3 {
|
||||
fmt.Println("The program needs at least 2 arguments!")
|
||||
return
|
||||
}
|
||||
|
||||
a1, _ := strconv.Atoi(arguments[1])
|
||||
a2, _ := strconv.Atoi(arguments[2])
|
||||
|
||||
fmt.Println(minMax(a1, a2))
|
||||
min, max := minMax(a1, a2)
|
||||
fmt.Println(min, max)
|
||||
|
||||
fmt.Println(namedMinMax(a1, a2))
|
||||
min, max = namedMinMax(a1, a2)
|
||||
fmt.Println(min, max)
|
||||
}
|
||||
17
ch06/returnPtr.go
Normal file
17
ch06/returnPtr.go
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func returnPtr(x int) *int {
|
||||
y := x * x
|
||||
return &y
|
||||
}
|
||||
|
||||
func main() {
|
||||
sq := returnPtr(10)
|
||||
fmt.Println("sq:", *sq)
|
||||
|
||||
fmt.Println("sq:", sq)
|
||||
}
|
||||
4
ch06/text.gotext
Normal file
4
ch06/text.gotext
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
Calculating the squares of some integers
|
||||
|
||||
{{ range . }} The square of {{ printf "%d" .Number}} is {{ printf "%d" .Square}}
|
||||
{{ end }}
|
||||
34
ch06/textT.go
Normal file
34
ch06/textT.go
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
type Entry struct {
|
||||
Number int
|
||||
Square int
|
||||
}
|
||||
|
||||
func main() {
|
||||
arguments := os.Args
|
||||
if len(arguments) != 2 {
|
||||
fmt.Println("Need the template file!")
|
||||
return
|
||||
}
|
||||
|
||||
tFile := arguments[1]
|
||||
DATA := [][]int{{-1, 1}, {-2, 4}, {-3, 9}, {-4, 16}}
|
||||
var Entries []Entry
|
||||
|
||||
for _, i := range DATA {
|
||||
if len(i) == 2 {
|
||||
temp := Entry{Number: i[0], Square: i[1]}
|
||||
Entries = append(Entries, temp)
|
||||
}
|
||||
}
|
||||
|
||||
t := template.Must(template.ParseGlob(tFile))
|
||||
t.Execute(os.Stdout, Entries)
|
||||
}
|
||||
13
ch06/useAPackage.go
Normal file
13
ch06/useAPackage.go
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"aPackage"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println("Using aPackage!")
|
||||
aPackage.A()
|
||||
aPackage.B()
|
||||
fmt.Println(aPackage.MyConstant)
|
||||
}
|
||||
23
ch06/useSyscall.go
Normal file
23
ch06/useSyscall.go
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func main() {
|
||||
pid, _, _ := syscall.Syscall(39, 0, 0, 0)
|
||||
fmt.Println("My pid is", pid)
|
||||
uid, _, _ := syscall.Syscall(24, 0, 0, 0)
|
||||
fmt.Println("User ID:", uid)
|
||||
|
||||
message := []byte{'H', 'e', 'l', 'l', 'o', '!', '\n'}
|
||||
fd := 1
|
||||
syscall.Write(fd, message)
|
||||
|
||||
fmt.Println("Using syscall.Exec()")
|
||||
command := "/bin/ls"
|
||||
env := os.Environ()
|
||||
syscall.Exec(command, []string{"ls", "-a", "-x"}, env)
|
||||
}
|
||||
64
ch07/advRefl.go
Normal file
64
ch07/advRefl.go
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
type t1 int
|
||||
type t2 int
|
||||
|
||||
type a struct {
|
||||
X int
|
||||
Y float64
|
||||
Text string
|
||||
}
|
||||
|
||||
func (a1 a) compareStruct(a2 a) bool {
|
||||
r1 := reflect.ValueOf(&a1).Elem()
|
||||
r2 := reflect.ValueOf(&a2).Elem()
|
||||
|
||||
for i := 0; i < r1.NumField(); i++ {
|
||||
if r1.Field(i).Interface() != r2.Field(i).Interface() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func printMethods(i interface{}) {
|
||||
r := reflect.ValueOf(i)
|
||||
t := r.Type()
|
||||
fmt.Printf("Type to examine: %s\n", t)
|
||||
|
||||
for j := 0; j < r.NumMethod(); j++ {
|
||||
m := r.Method(j).Type()
|
||||
fmt.Println(t.Method(j).Name, "-->", m)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
x1 := t1(100)
|
||||
x2 := t2(100)
|
||||
fmt.Printf("The type of x1 is %s\n", reflect.TypeOf(x1))
|
||||
fmt.Printf("The type of x2 is %s\n", reflect.TypeOf(x2))
|
||||
|
||||
var p struct{}
|
||||
r := reflect.New(reflect.ValueOf(&p).Type()).Elem()
|
||||
fmt.Printf("The type of r is %s\n", reflect.TypeOf(r))
|
||||
|
||||
a1 := a{1, 2.1, "A1"}
|
||||
a2 := a{1, -2, "A2"}
|
||||
|
||||
if a1.compareStruct(a1) {
|
||||
fmt.Println("Equal!")
|
||||
}
|
||||
|
||||
if !a1.compareStruct(a2) {
|
||||
fmt.Println("Not Equal!")
|
||||
}
|
||||
|
||||
var f *os.File
|
||||
printMethods(f)
|
||||
}
|
||||
27
ch07/assertion.go
Normal file
27
ch07/assertion.go
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var myInt interface{} = 123
|
||||
|
||||
k, ok := myInt.(int)
|
||||
if ok {
|
||||
fmt.Println("Success:", k)
|
||||
}
|
||||
|
||||
v, ok := myInt.(float64)
|
||||
if ok {
|
||||
fmt.Println(v)
|
||||
} else {
|
||||
fmt.Println("Failed without panicking!")
|
||||
}
|
||||
|
||||
i := myInt.(int)
|
||||
fmt.Println("No cheking:", i)
|
||||
|
||||
j := myInt.(bool)
|
||||
fmt.Println(j)
|
||||
}
|
||||
33
ch07/goCoIn.go
Normal file
33
ch07/goCoIn.go
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type first struct{}
|
||||
|
||||
func (a first) F() {
|
||||
a.shared()
|
||||
}
|
||||
|
||||
func (a first) shared() {
|
||||
fmt.Println("This is shared() from first!")
|
||||
}
|
||||
|
||||
type second struct {
|
||||
first
|
||||
}
|
||||
|
||||
func (a second) shared() {
|
||||
fmt.Println("This is shared() from second!")
|
||||
}
|
||||
|
||||
func main() {
|
||||
first{}.F()
|
||||
second{}.shared()
|
||||
i := second{}
|
||||
j := i.first
|
||||
j.F()
|
||||
// (i.first).F()
|
||||
// (second{}.first).F()
|
||||
}
|
||||
27
ch07/methods.go
Normal file
27
ch07/methods.go
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type twoInts struct {
|
||||
X int64
|
||||
Y int64
|
||||
}
|
||||
|
||||
func regularFunction(a, b twoInts) twoInts {
|
||||
temp := twoInts{X: a.X + b.X, Y: a.Y + b.Y}
|
||||
return temp
|
||||
}
|
||||
|
||||
func (a twoInts) method(b twoInts) twoInts {
|
||||
temp := twoInts{X: a.X + b.X, Y: a.Y + b.Y}
|
||||
return temp
|
||||
}
|
||||
|
||||
func main() {
|
||||
i := twoInts{X: 1, Y: 2}
|
||||
j := twoInts{X: -5, Y: -2}
|
||||
fmt.Println(regularFunction(i, j))
|
||||
fmt.Println(i.method(j))
|
||||
}
|
||||
6
ch07/myInterface.go
Normal file
6
ch07/myInterface.go
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
package myInterface
|
||||
|
||||
type Shape interface {
|
||||
Area() float64
|
||||
Perimeter() float64
|
||||
}
|
||||
34
ch07/ooo.go
Normal file
34
ch07/ooo.go
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type a struct {
|
||||
XX int
|
||||
YY int
|
||||
}
|
||||
|
||||
type b struct {
|
||||
AA string
|
||||
XX int
|
||||
}
|
||||
|
||||
type c struct {
|
||||
A a
|
||||
B b
|
||||
}
|
||||
|
||||
func (A a) A() {
|
||||
fmt.Println("Function A() for A")
|
||||
}
|
||||
|
||||
func (B b) A() {
|
||||
fmt.Println("Function A() for B")
|
||||
}
|
||||
|
||||
func main() {
|
||||
var i c
|
||||
i.A.A()
|
||||
i.B.A()
|
||||
}
|
||||
49
ch07/reflection.go
Normal file
49
ch07/reflection.go
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
type a struct {
|
||||
X int
|
||||
Y float64
|
||||
Z string
|
||||
}
|
||||
|
||||
type b struct {
|
||||
F int
|
||||
G int
|
||||
H string
|
||||
I float64
|
||||
}
|
||||
|
||||
func main() {
|
||||
x := 100
|
||||
xRefl := reflect.ValueOf(&x).Elem()
|
||||
xType := xRefl.Type()
|
||||
fmt.Printf("The type of x is %s.\n", xType)
|
||||
// fmt.Printf("The type of x is %s.\n", reflect.TypeOf(x))
|
||||
|
||||
A := a{100, 200.12, "Struct a"}
|
||||
B := b{1, 2, "Struct b", -1.2}
|
||||
var r reflect.Value
|
||||
|
||||
arguments := os.Args
|
||||
if len(arguments) == 1 {
|
||||
r = reflect.ValueOf(&A).Elem()
|
||||
} else {
|
||||
r = reflect.ValueOf(&B).Elem()
|
||||
}
|
||||
|
||||
iType := r.Type()
|
||||
fmt.Printf("i Type: %s\n", iType)
|
||||
fmt.Printf("The %d fields of %s are:\n", r.NumField(), iType)
|
||||
|
||||
for i := 0; i < r.NumField(); i++ {
|
||||
fmt.Printf("Field name: %s ", iType.Field(i).Name)
|
||||
fmt.Printf("with type: %s ", r.Field(i).Type())
|
||||
fmt.Printf("and value %v\n", r.Field(i).Interface())
|
||||
}
|
||||
}
|
||||
41
ch07/switch.go
Normal file
41
ch07/switch.go
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type square struct {
|
||||
X float64
|
||||
}
|
||||
|
||||
type circle struct {
|
||||
R float64
|
||||
}
|
||||
|
||||
type rectangle struct {
|
||||
X float64
|
||||
Y float64
|
||||
}
|
||||
|
||||
func tellInterface(x interface{}) {
|
||||
switch v := x.(type) {
|
||||
case square:
|
||||
fmt.Println("This is a square!")
|
||||
case circle:
|
||||
fmt.Printf("%v is a circle!\n", v)
|
||||
case rectangle:
|
||||
fmt.Println("This is a rectangle!")
|
||||
default:
|
||||
fmt.Printf("Unknown type %T!\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
x := circle{R: 10}
|
||||
tellInterface(x)
|
||||
y := rectangle{X: 4, Y: 1}
|
||||
tellInterface(y)
|
||||
z := square{X: 4}
|
||||
tellInterface(z)
|
||||
tellInterface(10)
|
||||
}
|
||||
54
ch07/useInterface.go
Normal file
54
ch07/useInterface.go
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"myInterface"
|
||||
)
|
||||
|
||||
type square struct {
|
||||
X float64
|
||||
}
|
||||
|
||||
type circle struct {
|
||||
R float64
|
||||
}
|
||||
|
||||
func (s square) Area() float64 {
|
||||
return s.X * s.X
|
||||
}
|
||||
|
||||
func (s square) Perimeter() float64 {
|
||||
return 4 * s.X
|
||||
}
|
||||
|
||||
func (s circle) Area() float64 {
|
||||
return s.R * s.R * math.Pi
|
||||
}
|
||||
|
||||
func (s circle) Perimeter() float64 {
|
||||
return 2 * s.R * math.Pi
|
||||
}
|
||||
|
||||
func Calculate(x myInterface.Shape) {
|
||||
_, ok := x.(circle)
|
||||
if ok {
|
||||
fmt.Println("Is a circle!")
|
||||
}
|
||||
|
||||
v, ok := x.(square)
|
||||
if ok {
|
||||
fmt.Println("Is a square:", v)
|
||||
}
|
||||
|
||||
fmt.Println(x.Area())
|
||||
fmt.Println(x.Perimeter())
|
||||
}
|
||||
|
||||
func main() {
|
||||
x := square{X: 10}
|
||||
fmt.Println("Perimeter:", x.Perimeter())
|
||||
Calculate(x)
|
||||
y := circle{R: 5}
|
||||
Calculate(y)
|
||||
}
|
||||
65
ch08/CSVplot.go
Normal file
65
ch08/CSVplot.go
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"github.com/Arafatk/glot"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 2 {
|
||||
fmt.Println("Need a data file!")
|
||||
return
|
||||
}
|
||||
|
||||
file := os.Args[1]
|
||||
_, err := os.Stat(file)
|
||||
if err != nil {
|
||||
fmt.Println("Cannot stat", file)
|
||||
return
|
||||
}
|
||||
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
fmt.Println("Cannot open", file)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
reader := csv.NewReader(f)
|
||||
reader.FieldsPerRecord = -1
|
||||
allRecords, err := reader.ReadAll()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
xP := []float64{}
|
||||
yP := []float64{}
|
||||
for _, rec := range allRecords {
|
||||
x, _ := strconv.ParseFloat(rec[0], 64)
|
||||
y, _ := strconv.ParseFloat(rec[1], 64)
|
||||
xP = append(xP, x)
|
||||
yP = append(yP, y)
|
||||
}
|
||||
|
||||
points := [][]float64{}
|
||||
points = append(points, xP)
|
||||
points = append(points, yP)
|
||||
fmt.Println(points)
|
||||
|
||||
dimensions := 2
|
||||
persist := true
|
||||
debug := false
|
||||
plot, _ := glot.NewPlot(dimensions, persist, debug)
|
||||
|
||||
plot.SetTitle("Using Glot with CSV data")
|
||||
plot.SetXLabel("X-Axis")
|
||||
plot.SetYLabel("Y-Axis")
|
||||
style := "circle"
|
||||
plot.AddPointGroup("Circle:", style, points)
|
||||
plot.SavePlot("output.png")
|
||||
}
|
||||
303
ch08/SYSCALLS
Normal file
303
ch08/SYSCALLS
Normal file
|
|
@ -0,0 +1,303 @@
|
|||
SYS_READ = 0
|
||||
SYS_WRITE = 1
|
||||
SYS_OPEN = 2
|
||||
SYS_CLOSE = 3
|
||||
SYS_STAT = 4
|
||||
SYS_FSTAT = 5
|
||||
SYS_LSTAT = 6
|
||||
SYS_POLL = 7
|
||||
SYS_LSEEK = 8
|
||||
SYS_MMAP = 9
|
||||
SYS_MPROTECT = 10
|
||||
SYS_MUNMAP = 11
|
||||
SYS_BRK = 12
|
||||
SYS_RT_SIGACTION = 13
|
||||
SYS_RT_SIGPROCMASK = 14
|
||||
SYS_RT_SIGRETURN = 15
|
||||
SYS_IOCTL = 16
|
||||
SYS_PREAD64 = 17
|
||||
SYS_PWRITE64 = 18
|
||||
SYS_READV = 19
|
||||
SYS_WRITEV = 20
|
||||
SYS_ACCESS = 21
|
||||
SYS_PIPE = 22
|
||||
SYS_SELECT = 23
|
||||
SYS_SCHED_YIELD = 24
|
||||
SYS_MREMAP = 25
|
||||
SYS_MSYNC = 26
|
||||
SYS_MINCORE = 27
|
||||
SYS_MADVISE = 28
|
||||
SYS_SHMGET = 29
|
||||
SYS_SHMAT = 30
|
||||
SYS_SHMCTL = 31
|
||||
SYS_DUP = 32
|
||||
SYS_DUP2 = 33
|
||||
SYS_PAUSE = 34
|
||||
SYS_NANOSLEEP = 35
|
||||
SYS_GETITIMER = 36
|
||||
SYS_ALARM = 37
|
||||
SYS_SETITIMER = 38
|
||||
SYS_GETPID = 39
|
||||
SYS_SENDFILE = 40
|
||||
SYS_SOCKET = 41
|
||||
SYS_CONNECT = 42
|
||||
SYS_ACCEPT = 43
|
||||
SYS_SENDTO = 44
|
||||
SYS_RECVFROM = 45
|
||||
SYS_SENDMSG = 46
|
||||
SYS_RECVMSG = 47
|
||||
SYS_SHUTDOWN = 48
|
||||
SYS_BIND = 49
|
||||
SYS_LISTEN = 50
|
||||
SYS_GETSOCKNAME = 51
|
||||
SYS_GETPEERNAME = 52
|
||||
SYS_SOCKETPAIR = 53
|
||||
SYS_SETSOCKOPT = 54
|
||||
SYS_GETSOCKOPT = 55
|
||||
SYS_CLONE = 56
|
||||
SYS_FORK = 57
|
||||
SYS_VFORK = 58
|
||||
SYS_EXECVE = 59
|
||||
SYS_EXIT = 60
|
||||
SYS_WAIT4 = 61
|
||||
SYS_KILL = 62
|
||||
SYS_UNAME = 63
|
||||
SYS_SEMGET = 64
|
||||
SYS_SEMOP = 65
|
||||
SYS_SEMCTL = 66
|
||||
SYS_SHMDT = 67
|
||||
SYS_MSGGET = 68
|
||||
SYS_MSGSND = 69
|
||||
SYS_MSGRCV = 70
|
||||
SYS_MSGCTL = 71
|
||||
SYS_FCNTL = 72
|
||||
SYS_FLOCK = 73
|
||||
SYS_FSYNC = 74
|
||||
SYS_FDATASYNC = 75
|
||||
SYS_TRUNCATE = 76
|
||||
SYS_FTRUNCATE = 77
|
||||
SYS_GETDENTS = 78
|
||||
SYS_GETCWD = 79
|
||||
SYS_CHDIR = 80
|
||||
SYS_FCHDIR = 81
|
||||
SYS_RENAME = 82
|
||||
SYS_MKDIR = 83
|
||||
SYS_RMDIR = 84
|
||||
SYS_CREAT = 85
|
||||
SYS_LINK = 86
|
||||
SYS_UNLINK = 87
|
||||
SYS_SYMLINK = 88
|
||||
SYS_READLINK = 89
|
||||
SYS_CHMOD = 90
|
||||
SYS_FCHMOD = 91
|
||||
SYS_CHOWN = 92
|
||||
SYS_FCHOWN = 93
|
||||
SYS_LCHOWN = 94
|
||||
SYS_UMASK = 95
|
||||
SYS_GETTIMEOFDAY = 96
|
||||
SYS_GETRLIMIT = 97
|
||||
SYS_GETRUSAGE = 98
|
||||
SYS_SYSINFO = 99
|
||||
SYS_TIMES = 100
|
||||
SYS_PTRACE = 101
|
||||
SYS_GETUID = 102
|
||||
SYS_SYSLOG = 103
|
||||
SYS_GETGID = 104
|
||||
SYS_SETUID = 105
|
||||
SYS_SETGID = 106
|
||||
SYS_GETEUID = 107
|
||||
SYS_GETEGID = 108
|
||||
SYS_SETPGID = 109
|
||||
SYS_GETPPID = 110
|
||||
SYS_GETPGRP = 111
|
||||
SYS_SETSID = 112
|
||||
SYS_SETREUID = 113
|
||||
SYS_SETREGID = 114
|
||||
SYS_GETGROUPS = 115
|
||||
SYS_SETGROUPS = 116
|
||||
SYS_SETRESUID = 117
|
||||
SYS_GETRESUID = 118
|
||||
SYS_SETRESGID = 119
|
||||
SYS_GETRESGID = 120
|
||||
SYS_GETPGID = 121
|
||||
SYS_SETFSUID = 122
|
||||
SYS_SETFSGID = 123
|
||||
SYS_GETSID = 124
|
||||
SYS_CAPGET = 125
|
||||
SYS_CAPSET = 126
|
||||
SYS_RT_SIGPENDING = 127
|
||||
SYS_RT_SIGTIMEDWAIT = 128
|
||||
SYS_RT_SIGQUEUEINFO = 129
|
||||
SYS_RT_SIGSUSPEND = 130
|
||||
SYS_SIGALTSTACK = 131
|
||||
SYS_UTIME = 132
|
||||
SYS_MKNOD = 133
|
||||
SYS_USELIB = 134
|
||||
SYS_PERSONALITY = 135
|
||||
SYS_USTAT = 136
|
||||
SYS_STATFS = 137
|
||||
SYS_FSTATFS = 138
|
||||
SYS_SYSFS = 139
|
||||
SYS_GETPRIORITY = 140
|
||||
SYS_SETPRIORITY = 141
|
||||
SYS_SCHED_SETPARAM = 142
|
||||
SYS_SCHED_GETPARAM = 143
|
||||
SYS_SCHED_SETSCHEDULER = 144
|
||||
SYS_SCHED_GETSCHEDULER = 145
|
||||
SYS_SCHED_GET_PRIORITY_MAX = 146
|
||||
SYS_SCHED_GET_PRIORITY_MIN = 147
|
||||
SYS_SCHED_RR_GET_INTERVAL = 148
|
||||
SYS_MLOCK = 149
|
||||
SYS_MUNLOCK = 150
|
||||
SYS_MLOCKALL = 151
|
||||
SYS_MUNLOCKALL = 152
|
||||
SYS_VHANGUP = 153
|
||||
SYS_MODIFY_LDT = 154
|
||||
SYS_PIVOT_ROOT = 155
|
||||
SYS__SYSCTL = 156
|
||||
SYS_PRCTL = 157
|
||||
SYS_ARCH_PRCTL = 158
|
||||
SYS_ADJTIMEX = 159
|
||||
SYS_SETRLIMIT = 160
|
||||
SYS_CHROOT = 161
|
||||
SYS_SYNC = 162
|
||||
SYS_ACCT = 163
|
||||
SYS_SETTIMEOFDAY = 164
|
||||
SYS_MOUNT = 165
|
||||
SYS_UMOUNT2 = 166
|
||||
SYS_SWAPON = 167
|
||||
SYS_SWAPOFF = 168
|
||||
SYS_REBOOT = 169
|
||||
SYS_SETHOSTNAME = 170
|
||||
SYS_SETDOMAINNAME = 171
|
||||
SYS_IOPL = 172
|
||||
SYS_IOPERM = 173
|
||||
SYS_CREATE_MODULE = 174
|
||||
SYS_INIT_MODULE = 175
|
||||
SYS_DELETE_MODULE = 176
|
||||
SYS_GET_KERNEL_SYMS = 177
|
||||
SYS_QUERY_MODULE = 178
|
||||
SYS_QUOTACTL = 179
|
||||
SYS_NFSSERVCTL = 180
|
||||
SYS_GETPMSG = 181
|
||||
SYS_PUTPMSG = 182
|
||||
SYS_AFS_SYSCALL = 183
|
||||
SYS_TUXCALL = 184
|
||||
SYS_SECURITY = 185
|
||||
SYS_GETTID = 186
|
||||
SYS_READAHEAD = 187
|
||||
SYS_SETXATTR = 188
|
||||
SYS_LSETXATTR = 189
|
||||
SYS_FSETXATTR = 190
|
||||
SYS_GETXATTR = 191
|
||||
SYS_LGETXATTR = 192
|
||||
SYS_FGETXATTR = 193
|
||||
SYS_LISTXATTR = 194
|
||||
SYS_LLISTXATTR = 195
|
||||
SYS_FLISTXATTR = 196
|
||||
SYS_REMOVEXATTR = 197
|
||||
SYS_LREMOVEXATTR = 198
|
||||
SYS_FREMOVEXATTR = 199
|
||||
SYS_TKILL = 200
|
||||
SYS_TIME = 201
|
||||
SYS_FUTEX = 202
|
||||
SYS_SCHED_SETAFFINITY = 203
|
||||
SYS_SCHED_GETAFFINITY = 204
|
||||
SYS_SET_THREAD_AREA = 205
|
||||
SYS_IO_SETUP = 206
|
||||
SYS_IO_DESTROY = 207
|
||||
SYS_IO_GETEVENTS = 208
|
||||
SYS_IO_SUBMIT = 209
|
||||
SYS_IO_CANCEL = 210
|
||||
SYS_GET_THREAD_AREA = 211
|
||||
SYS_LOOKUP_DCOOKIE = 212
|
||||
SYS_EPOLL_CREATE = 213
|
||||
SYS_EPOLL_CTL_OLD = 214
|
||||
SYS_EPOLL_WAIT_OLD = 215
|
||||
SYS_REMAP_FILE_PAGES = 216
|
||||
SYS_GETDENTS64 = 217
|
||||
SYS_SET_TID_ADDRESS = 218
|
||||
SYS_RESTART_SYSCALL = 219
|
||||
SYS_SEMTIMEDOP = 220
|
||||
SYS_FADVISE64 = 221
|
||||
SYS_TIMER_CREATE = 222
|
||||
SYS_TIMER_SETTIME = 223
|
||||
SYS_TIMER_GETTIME = 224
|
||||
SYS_TIMER_GETOVERRUN = 225
|
||||
SYS_TIMER_DELETE = 226
|
||||
SYS_CLOCK_SETTIME = 227
|
||||
SYS_CLOCK_GETTIME = 228
|
||||
SYS_CLOCK_GETRES = 229
|
||||
SYS_CLOCK_NANOSLEEP = 230
|
||||
SYS_EXIT_GROUP = 231
|
||||
SYS_EPOLL_WAIT = 232
|
||||
SYS_EPOLL_CTL = 233
|
||||
SYS_TGKILL = 234
|
||||
SYS_UTIMES = 235
|
||||
SYS_VSERVER = 236
|
||||
SYS_MBIND = 237
|
||||
SYS_SET_MEMPOLICY = 238
|
||||
SYS_GET_MEMPOLICY = 239
|
||||
SYS_MQ_OPEN = 240
|
||||
SYS_MQ_UNLINK = 241
|
||||
SYS_MQ_TIMEDSEND = 242
|
||||
SYS_MQ_TIMEDRECEIVE = 243
|
||||
SYS_MQ_NOTIFY = 244
|
||||
SYS_MQ_GETSETATTR = 245
|
||||
SYS_KEXEC_LOAD = 246
|
||||
SYS_WAITID = 247
|
||||
SYS_ADD_KEY = 248
|
||||
SYS_REQUEST_KEY = 249
|
||||
SYS_KEYCTL = 250
|
||||
SYS_IOPRIO_SET = 251
|
||||
SYS_IOPRIO_GET = 252
|
||||
SYS_INOTIFY_INIT = 253
|
||||
SYS_INOTIFY_ADD_WATCH = 254
|
||||
SYS_INOTIFY_RM_WATCH = 255
|
||||
SYS_MIGRATE_PAGES = 256
|
||||
SYS_OPENAT = 257
|
||||
SYS_MKDIRAT = 258
|
||||
SYS_MKNODAT = 259
|
||||
SYS_FCHOWNAT = 260
|
||||
SYS_FUTIMESAT = 261
|
||||
SYS_NEWFSTATAT = 262
|
||||
SYS_UNLINKAT = 263
|
||||
SYS_RENAMEAT = 264
|
||||
SYS_LINKAT = 265
|
||||
SYS_SYMLINKAT = 266
|
||||
SYS_READLINKAT = 267
|
||||
SYS_FCHMODAT = 268
|
||||
SYS_FACCESSAT = 269
|
||||
SYS_PSELECT6 = 270
|
||||
SYS_PPOLL = 271
|
||||
SYS_UNSHARE = 272
|
||||
SYS_SET_ROBUST_LIST = 273
|
||||
SYS_GET_ROBUST_LIST = 274
|
||||
SYS_SPLICE = 275
|
||||
SYS_TEE = 276
|
||||
SYS_SYNC_FILE_RANGE = 277
|
||||
SYS_VMSPLICE = 278
|
||||
SYS_MOVE_PAGES = 279
|
||||
SYS_UTIMENSAT = 280
|
||||
SYS_EPOLL_PWAIT = 281
|
||||
SYS_SIGNALFD = 282
|
||||
SYS_TIMERFD_CREATE = 283
|
||||
SYS_EVENTFD = 284
|
||||
SYS_FALLOCATE = 285
|
||||
SYS_TIMERFD_SETTIME = 286
|
||||
SYS_TIMERFD_GETTIME = 287
|
||||
SYS_ACCEPT4 = 288
|
||||
SYS_SIGNALFD4 = 289
|
||||
SYS_EVENTFD2 = 290
|
||||
SYS_EPOLL_CREATE1 = 291
|
||||
SYS_DUP3 = 292
|
||||
SYS_PIPE2 = 293
|
||||
SYS_INOTIFY_INIT1 = 294
|
||||
SYS_PREADV = 295
|
||||
SYS_PWRITEV = 296
|
||||
SYS_RT_TGSIGQUEUEINFO = 297
|
||||
SYS_PERF_EVENT_OPEN = 298
|
||||
SYS_RECVMMSG = 299
|
||||
SYS_FANOTIFY_INIT = 300
|
||||
SYS_FANOTIFY_MARK = 301
|
||||
SYS_PRLIMIT64 = 302
|
||||
49
ch08/byCharacter.go
Normal file
49
ch08/byCharacter.go
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
func charByChar(file string) error {
|
||||
var err error
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
r := bufio.NewReader(f)
|
||||
for {
|
||||
line, err := r.ReadString('\n')
|
||||
if err == io.EOF {
|
||||
break
|
||||
} else if err != nil {
|
||||
fmt.Printf("error reading file %s", err)
|
||||
return err
|
||||
}
|
||||
|
||||
for _, x := range line {
|
||||
fmt.Println(string(x))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
if len(flag.Args()) == 0 {
|
||||
fmt.Printf("usage: byChar <file1> [<file2> ...]\n")
|
||||
return
|
||||
}
|
||||
|
||||
for _, file := range flag.Args() {
|
||||
err := charByChar(file)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
47
ch08/byLine.go
Normal file
47
ch08/byLine.go
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
func lineByLine(file string) error {
|
||||
var err error
|
||||
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
r := bufio.NewReader(f)
|
||||
for {
|
||||
line, err := r.ReadString('\n')
|
||||
if err == io.EOF {
|
||||
break
|
||||
} else if err != nil {
|
||||
fmt.Printf("error reading file %s", err)
|
||||
break
|
||||
}
|
||||
fmt.Print(line)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
if len(flag.Args()) == 0 {
|
||||
fmt.Printf("usage: byLine <file1> [<file2> ...]\n")
|
||||
return
|
||||
}
|
||||
|
||||
for _, file := range flag.Args() {
|
||||
err := lineByLine(file)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
52
ch08/byWord.go
Normal file
52
ch08/byWord.go
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
func wordByWord(file string) error {
|
||||
var err error
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
r := bufio.NewReader(f)
|
||||
for {
|
||||
line, err := r.ReadString('\n')
|
||||
if err == io.EOF {
|
||||
break
|
||||
} else if err != nil {
|
||||
fmt.Printf("error reading file %s", err)
|
||||
return err
|
||||
}
|
||||
|
||||
r := regexp.MustCompile("[^\\s]+")
|
||||
words := r.FindAllString(line, -1)
|
||||
for i := 0; i < len(words); i++ {
|
||||
fmt.Println(words[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
if len(flag.Args()) == 0 {
|
||||
fmt.Printf("usage: byWord <file1> [<file2> ...]\n")
|
||||
return
|
||||
}
|
||||
|
||||
for _, file := range flag.Args() {
|
||||
err := wordByWord(file)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
34
ch08/bytes.go
Normal file
34
ch08/bytes.go
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var buffer bytes.Buffer
|
||||
buffer.Write([]byte("This is"))
|
||||
fmt.Fprintf(&buffer, " a string!\n")
|
||||
buffer.WriteTo(os.Stdout)
|
||||
buffer.WriteTo(os.Stdout)
|
||||
|
||||
buffer.Reset()
|
||||
buffer.Write([]byte("Mastering Go!"))
|
||||
r := bytes.NewReader([]byte(buffer.String()))
|
||||
fmt.Println(buffer.String())
|
||||
for {
|
||||
b := make([]byte, 3)
|
||||
n, err := r.Read(b)
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
continue
|
||||
}
|
||||
fmt.Printf("Read %s Bytes: %d\n", b, n)
|
||||
}
|
||||
}
|
||||
39
ch08/cat.go
Normal file
39
ch08/cat.go
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
func printFile(filename string) error {
|
||||
f, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
scanner := bufio.NewScanner(f)
|
||||
for scanner.Scan() {
|
||||
io.WriteString(os.Stdout, scanner.Text())
|
||||
io.WriteString(os.Stdout, "\n")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
filename := ""
|
||||
arguments := os.Args
|
||||
if len(arguments) == 1 {
|
||||
io.Copy(os.Stdout, os.Stdin)
|
||||
return
|
||||
}
|
||||
|
||||
for i := 1; i < len(arguments); i++ {
|
||||
filename = arguments[i]
|
||||
err := printFile(filename)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
10
ch08/dataFile
Normal file
10
ch08/dataFile
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
1,2
|
||||
2,3
|
||||
3,3
|
||||
4,4
|
||||
5,8
|
||||
6,5
|
||||
-1,12
|
||||
-2,10
|
||||
-3,10
|
||||
-4,10
|
||||
21
ch08/devRandom.go
Normal file
21
ch08/devRandom.go
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
f, err := os.Open("/dev/random")
|
||||
defer f.Close()
|
||||
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
var seed int64
|
||||
binary.Read(f, binary.LittleEndian, &seed)
|
||||
fmt.Println("Seed:", seed)
|
||||
}
|
||||
12
ch08/ebpf.go
Normal file
12
ch08/ebpf.go
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/iovisor/gobpf"
|
||||
"os"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
}
|
||||
51
ch08/funWithFlag.go
Normal file
51
ch08/funWithFlag.go
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type NamesFlag struct {
|
||||
Names []string
|
||||
}
|
||||
|
||||
func (s *NamesFlag) GetNames() []string {
|
||||
return s.Names
|
||||
}
|
||||
|
||||
func (s *NamesFlag) String() string {
|
||||
return fmt.Sprint(s.Names)
|
||||
}
|
||||
|
||||
func (s *NamesFlag) Set(v string) error {
|
||||
if len(s.Names) > 0 {
|
||||
return fmt.Errorf("Cannot use names flag more than once!")
|
||||
}
|
||||
|
||||
names := strings.Split(v, ",")
|
||||
for _, item := range names {
|
||||
s.Names = append(s.Names, item)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
var manyNames NamesFlag
|
||||
minusK := flag.Int("k", 0, "An int")
|
||||
minusO := flag.String("o", "Mihalis", "The name")
|
||||
flag.Var(&manyNames, "names", "Comma-separated list")
|
||||
|
||||
flag.Parse()
|
||||
fmt.Println("-k:", *minusK)
|
||||
fmt.Println("-o:", *minusO)
|
||||
|
||||
for i, item := range manyNames.GetNames() {
|
||||
fmt.Println(i, item)
|
||||
}
|
||||
|
||||
fmt.Println("Remaining command line arguments:")
|
||||
for index, val := range flag.Args() {
|
||||
fmt.Println(index, ":", val)
|
||||
}
|
||||
}
|
||||
53
ch08/goFind.go
Normal file
53
ch08/goFind.go
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
var minusD bool = false
|
||||
var minusF bool = false
|
||||
|
||||
func walk(path string, info os.FileInfo, err error) error {
|
||||
fileInfo, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
mode := fileInfo.Mode()
|
||||
if mode.IsRegular() && minusF {
|
||||
fmt.Println("+", path)
|
||||
return nil
|
||||
}
|
||||
|
||||
if mode.IsDir() && minusD {
|
||||
fmt.Println("*", path)
|
||||
return nil
|
||||
}
|
||||
|
||||
fmt.Println(path)
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
starD := flag.Bool("d", false, "Signify directories")
|
||||
plusF := flag.Bool("f", false, "Signify regular files")
|
||||
flag.Parse()
|
||||
flags := flag.Args()
|
||||
|
||||
Path := "."
|
||||
if len(flags) == 1 {
|
||||
Path = flags[0]
|
||||
}
|
||||
|
||||
minusD = *starD
|
||||
minusF = *plusF
|
||||
|
||||
err := filepath.Walk(Path, walk)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
39
ch08/handleAll.go
Normal file
39
ch08/handleAll.go
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func handle(signal os.Signal) {
|
||||
fmt.Println("Received:", signal)
|
||||
}
|
||||
|
||||
func main() {
|
||||
sigs := make(chan os.Signal, 1)
|
||||
signal.Notify(sigs)
|
||||
go func() {
|
||||
for {
|
||||
sig := <-sigs
|
||||
switch sig {
|
||||
case os.Interrupt:
|
||||
handle(sig)
|
||||
case syscall.SIGTERM:
|
||||
handle(sig)
|
||||
os.Exit(0)
|
||||
case syscall.SIGUSR2:
|
||||
fmt.Println("Handling syscall.SIGUSR2!")
|
||||
default:
|
||||
fmt.Println("Ignoring:", sig)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
fmt.Printf(".")
|
||||
time.Sleep(30 * time.Second)
|
||||
}
|
||||
}
|
||||
35
ch08/handleTwo.go
Normal file
35
ch08/handleTwo.go
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func handleSignal(signal os.Signal) {
|
||||
fmt.Println("handleSignal() Caught:", signal)
|
||||
}
|
||||
|
||||
func main() {
|
||||
sigs := make(chan os.Signal, 1)
|
||||
signal.Notify(sigs, os.Interrupt, syscall.SIGINFO)
|
||||
go func() {
|
||||
for {
|
||||
sig := <-sigs
|
||||
switch sig {
|
||||
case os.Interrupt:
|
||||
fmt.Println("Caught:", sig)
|
||||
case syscall.SIGINFO:
|
||||
handleSignal(sig)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
fmt.Printf(".")
|
||||
time.Sleep(20 * time.Second)
|
||||
}
|
||||
}
|
||||
20
ch08/ids.go
Normal file
20
ch08/ids.go
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/user"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println("User id:", os.Getuid())
|
||||
|
||||
var u *user.User
|
||||
u, _ = user.Current()
|
||||
fmt.Print("Group ids: ")
|
||||
groupIDs, _ := u.GroupIds()
|
||||
for _, i := range groupIDs {
|
||||
fmt.Print(i, " ")
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
161
ch08/kvSaveLoad.go
Normal file
161
ch08/kvSaveLoad.go
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/gob"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type myElement struct {
|
||||
Name string
|
||||
Surname string
|
||||
Id string
|
||||
}
|
||||
|
||||
var DATA = make(map[string]myElement)
|
||||
var DATAFILE = "/tmp/dataFile.gob"
|
||||
|
||||
func save() error {
|
||||
fmt.Println("Saving", DATAFILE)
|
||||
err := os.Remove(DATAFILE)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
|
||||
saveTo, err := os.Create(DATAFILE)
|
||||
if err != nil {
|
||||
fmt.Println("Cannot create", DATAFILE)
|
||||
return err
|
||||
}
|
||||
defer saveTo.Close()
|
||||
|
||||
encoder := gob.NewEncoder(saveTo)
|
||||
err = encoder.Encode(DATA)
|
||||
if err != nil {
|
||||
fmt.Println("Cannot save to", DATAFILE)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func load() error {
|
||||
fmt.Println("Loading", DATAFILE)
|
||||
loadFrom, err := os.Open(DATAFILE)
|
||||
defer loadFrom.Close()
|
||||
if err != nil {
|
||||
fmt.Println("Empty key/value store!")
|
||||
return err
|
||||
}
|
||||
|
||||
decoder := gob.NewDecoder(loadFrom)
|
||||
decoder.Decode(&DATA)
|
||||
return nil
|
||||
}
|
||||
|
||||
func ADD(k string, n myElement) bool {
|
||||
if k == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if LOOKUP(k) == nil {
|
||||
DATA[k] = n
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func DELETE(k string) bool {
|
||||
if LOOKUP(k) != nil {
|
||||
delete(DATA, k)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func LOOKUP(k string) *myElement {
|
||||
_, ok := DATA[k]
|
||||
if ok {
|
||||
n := DATA[k]
|
||||
return &n
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func CHANGE(k string, n myElement) bool {
|
||||
DATA[k] = n
|
||||
return true
|
||||
}
|
||||
|
||||
func PRINT() {
|
||||
for k, d := range DATA {
|
||||
fmt.Printf("key: %s value: %v\n", k, d)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
err := load()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
for scanner.Scan() {
|
||||
text := scanner.Text()
|
||||
text = strings.TrimSpace(text)
|
||||
tokens := strings.Fields(text)
|
||||
|
||||
switch len(tokens) {
|
||||
case 0:
|
||||
continue
|
||||
case 1:
|
||||
tokens = append(tokens, "")
|
||||
tokens = append(tokens, "")
|
||||
tokens = append(tokens, "")
|
||||
tokens = append(tokens, "")
|
||||
case 2:
|
||||
tokens = append(tokens, "")
|
||||
tokens = append(tokens, "")
|
||||
tokens = append(tokens, "")
|
||||
case 3:
|
||||
tokens = append(tokens, "")
|
||||
tokens = append(tokens, "")
|
||||
case 4:
|
||||
tokens = append(tokens, "")
|
||||
}
|
||||
|
||||
switch tokens[0] {
|
||||
case "PRINT":
|
||||
PRINT()
|
||||
case "STOP":
|
||||
err = save()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
return
|
||||
case "DELETE":
|
||||
if !DELETE(tokens[1]) {
|
||||
fmt.Println("Delete operation failed!")
|
||||
}
|
||||
case "ADD":
|
||||
n := myElement{tokens[2], tokens[3], tokens[4]}
|
||||
if !ADD(tokens[1], n) {
|
||||
fmt.Println("Add operation failed!")
|
||||
}
|
||||
case "LOOKUP":
|
||||
n := LOOKUP(tokens[1])
|
||||
if n != nil {
|
||||
fmt.Printf("%v\n", *n)
|
||||
}
|
||||
case "CHANGE":
|
||||
n := myElement{tokens[2], tokens[3], tokens[4]}
|
||||
if !CHANGE(tokens[1], n) {
|
||||
fmt.Println("Update operation failed!")
|
||||
}
|
||||
default:
|
||||
fmt.Println("Unknown command – please try again!")
|
||||
}
|
||||
}
|
||||
}
|
||||
19
ch08/permissions.go
Normal file
19
ch08/permissions.go
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
arguments := os.Args
|
||||
if len(arguments) == 1 {
|
||||
fmt.Printf("usage: permissions filename\n")
|
||||
return
|
||||
}
|
||||
|
||||
filename := arguments[1]
|
||||
info, _ := os.Stat(filename)
|
||||
mode := info.Mode()
|
||||
fmt.Println(filename, "mode is", mode.String()[1:10])
|
||||
}
|
||||
38
ch08/ptraceRegs.go
Normal file
38
ch08/ptraceRegs.go
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var r syscall.PtraceRegs
|
||||
cmd := exec.Command(os.Args[1], os.Args[2:]...)
|
||||
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Ptrace: true}
|
||||
err := cmd.Start()
|
||||
if err != nil {
|
||||
fmt.Println("Start:", err)
|
||||
return
|
||||
}
|
||||
|
||||
err = cmd.Wait()
|
||||
fmt.Printf("State: %v\n", err)
|
||||
wpid := cmd.Process.Pid
|
||||
|
||||
err = syscall.PtraceGetRegs(wpid, &r)
|
||||
if err != nil {
|
||||
fmt.Println("PtraceGetRegs:", err)
|
||||
return
|
||||
}
|
||||
fmt.Printf("Registers: %#v\n", r)
|
||||
fmt.Printf("R15=%d, Gs=%d\n", r.R15, r.Gs)
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
55
ch08/readSize.go
Normal file
55
ch08/readSize.go
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func readSize(f *os.File, size int) []byte {
|
||||
buffer := make([]byte, size)
|
||||
|
||||
n, err := f.Read(buffer)
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return nil
|
||||
}
|
||||
|
||||
return buffer[0:n]
|
||||
}
|
||||
|
||||
func main() {
|
||||
arguments := os.Args
|
||||
if len(arguments) != 3 {
|
||||
fmt.Println("<buffer size> <filename>")
|
||||
return
|
||||
}
|
||||
|
||||
bufferSize, err := strconv.Atoi(os.Args[1])
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
file := os.Args[2]
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
for {
|
||||
readData := readSize(f, bufferSize)
|
||||
if readData != nil {
|
||||
fmt.Print(string(readData))
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
59
ch08/save.go
Normal file
59
ch08/save.go
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
s := []byte("Data to write\n")
|
||||
|
||||
f1, err := os.Create("f1.txt")
|
||||
if err != nil {
|
||||
fmt.Println("Cannot create file", err)
|
||||
return
|
||||
}
|
||||
defer f1.Close()
|
||||
fmt.Fprintf(f1, string(s))
|
||||
|
||||
f2, err := os.Create("f2.txt")
|
||||
if err != nil {
|
||||
fmt.Println("Cannot create file", err)
|
||||
return
|
||||
}
|
||||
defer f2.Close()
|
||||
n, err := f2.WriteString(string(s))
|
||||
fmt.Printf("wrote %d bytes\n", n)
|
||||
|
||||
f3, err := os.Create("f3.txt")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
w := bufio.NewWriter(f3)
|
||||
n, err = w.WriteString(string(s))
|
||||
fmt.Printf("wrote %d bytes\n", n)
|
||||
w.Flush()
|
||||
|
||||
f4 := "f4.txt"
|
||||
err = ioutil.WriteFile(f4, s, 0644)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
f5, err := os.Create("f5.txt")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
n, err = io.WriteString(f5, string(s))
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
fmt.Printf("wrote %d bytes\n", n)
|
||||
}
|
||||
18
ch08/simpleFlag.go
Normal file
18
ch08/simpleFlag.go
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func main() {
|
||||
minusK := flag.Bool("k", true, "k")
|
||||
minusO := flag.Int("O", 1, "O")
|
||||
flag.Parse()
|
||||
|
||||
valueK := *minusK
|
||||
valueO := *minusO
|
||||
valueO++
|
||||
fmt.Println("-k:", valueK)
|
||||
fmt.Println("-O:", valueO)
|
||||
}
|
||||
38
ch08/str.go
Normal file
38
ch08/str.go
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
r := strings.NewReader("test")
|
||||
fmt.Println("r length:", r.Len())
|
||||
|
||||
b := make([]byte, 1)
|
||||
for {
|
||||
n, err := r.Read(b)
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
continue
|
||||
}
|
||||
fmt.Printf("Read %s Bytes: %d\n", b, n)
|
||||
}
|
||||
|
||||
s := strings.NewReader("This is an error!\n")
|
||||
fmt.Println("r length:", s.Len())
|
||||
n, err := s.WriteTo(os.Stderr)
|
||||
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
fmt.Printf("Wrote %d bytes to os.Stderr\n", n)
|
||||
}
|
||||
90
ch08/traceSyscall.go
Normal file
90
ch08/traceSyscall.go
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
var maxSyscalls = 0
|
||||
|
||||
const SYSCALLFILE = "SYSCALLS"
|
||||
|
||||
func main() {
|
||||
var SYSTEMCALLS []string
|
||||
f, err := os.Open(SYSCALLFILE)
|
||||
defer f.Close()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
scanner := bufio.NewScanner(f)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
line = strings.Replace(line, " ", "", -1)
|
||||
line = strings.Replace(line, "SYS_", "", -1)
|
||||
temp := strings.ToLower(strings.Split(line, "=")[0])
|
||||
SYSTEMCALLS = append(SYSTEMCALLS, temp)
|
||||
maxSyscalls++
|
||||
}
|
||||
|
||||
COUNTER := make([]int, maxSyscalls)
|
||||
var regs syscall.PtraceRegs
|
||||
cmd := exec.Command(os.Args[1], os.Args[2:]...)
|
||||
|
||||
cmd.Stdin = os.Stdin
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Ptrace: true}
|
||||
|
||||
err = cmd.Start()
|
||||
err = cmd.Wait()
|
||||
if err != nil {
|
||||
fmt.Println("Wait:", err)
|
||||
}
|
||||
|
||||
pid := cmd.Process.Pid
|
||||
fmt.Println("Process ID:", pid)
|
||||
|
||||
before := true
|
||||
forCount := 0
|
||||
for {
|
||||
if before {
|
||||
err := syscall.PtraceGetRegs(pid, ®s)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if regs.Orig_rax > uint64(maxSyscalls) {
|
||||
fmt.Println("Unknown:", regs.Orig_rax)
|
||||
return
|
||||
}
|
||||
|
||||
COUNTER[regs.Orig_rax]++
|
||||
forCount++
|
||||
}
|
||||
|
||||
err = syscall.PtraceSyscall(pid, 0)
|
||||
if err != nil {
|
||||
fmt.Println("PtraceSyscall:", err)
|
||||
return
|
||||
}
|
||||
|
||||
_, err = syscall.Wait4(pid, nil, 0, nil)
|
||||
if err != nil {
|
||||
fmt.Println("Wait4:", err)
|
||||
return
|
||||
}
|
||||
before = !before
|
||||
}
|
||||
|
||||
for i, x := range COUNTER {
|
||||
if x != 0 {
|
||||
fmt.Println(SYSTEMCALLS[i], "->", x)
|
||||
}
|
||||
}
|
||||
fmt.Println("Total System Calls:", forCount)
|
||||
}
|
||||
23
ch09/create.go
Normal file
23
ch09/create.go
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
n := flag.Int("n", 10, "Number of goroutines")
|
||||
flag.Parse()
|
||||
|
||||
count := *n
|
||||
fmt.Printf("Going to create %d goroutines.\n", count)
|
||||
for i := 0; i < count; i++ {
|
||||
go func(x int) {
|
||||
fmt.Printf("%d ", x)
|
||||
}(i)
|
||||
}
|
||||
|
||||
time.Sleep(time.Second)
|
||||
fmt.Println("\nExiting...")
|
||||
}
|
||||
74
ch09/pipeline.go
Normal file
74
ch09/pipeline.go
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
var CLOSEA = false
|
||||
|
||||
var DATA = make(map[int]bool)
|
||||
|
||||
func random(min, max int) int {
|
||||
return rand.Intn(max-min) + min
|
||||
}
|
||||
|
||||
func first(min, max int, out chan<- int) {
|
||||
for {
|
||||
if CLOSEA {
|
||||
close(out)
|
||||
return
|
||||
}
|
||||
out <- random(min, max)
|
||||
}
|
||||
}
|
||||
|
||||
func second(out chan<- int, in <-chan int) {
|
||||
for x := range in {
|
||||
fmt.Print(x, " ")
|
||||
_, ok := DATA[x]
|
||||
if ok {
|
||||
CLOSEA = true
|
||||
} else {
|
||||
DATA[x] = true
|
||||
out <- x
|
||||
}
|
||||
}
|
||||
fmt.Println()
|
||||
close(out)
|
||||
}
|
||||
|
||||
func third(in <-chan int) {
|
||||
var sum int
|
||||
sum = 0
|
||||
for x2 := range in {
|
||||
sum = sum + x2
|
||||
}
|
||||
fmt.Printf("The sum of the random numbers is %d\n", sum)
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 3 {
|
||||
fmt.Println("Need two integer parameters!")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
n1, _ := strconv.Atoi(os.Args[1])
|
||||
n2, _ := strconv.Atoi(os.Args[2])
|
||||
|
||||
if n1 > n2 {
|
||||
fmt.Printf("%d should be smaller than %d\n", n1, n2)
|
||||
return
|
||||
}
|
||||
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
A := make(chan int)
|
||||
B := make(chan int)
|
||||
|
||||
go first(n1, n2, A)
|
||||
go second(B, A)
|
||||
third(B)
|
||||
}
|
||||
28
ch09/readCh.go
Normal file
28
ch09/readCh.go
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func writeToChannel(c chan int, x int) {
|
||||
fmt.Println("1", x)
|
||||
c <- x
|
||||
close(c)
|
||||
fmt.Println("2", x)
|
||||
}
|
||||
|
||||
func main() {
|
||||
c := make(chan int)
|
||||
go writeToChannel(c, 10)
|
||||
time.Sleep(1 * time.Second)
|
||||
fmt.Println("Read:", <-c)
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
_, ok := <-c
|
||||
if ok {
|
||||
fmt.Println("Channel is open!")
|
||||
} else {
|
||||
fmt.Println("Channel is closed!")
|
||||
}
|
||||
}
|
||||
25
ch09/simple.go
Normal file
25
ch09/simple.go
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func function() {
|
||||
for i := 0; i < 10; i++ {
|
||||
fmt.Print(i)
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
func main() {
|
||||
go function()
|
||||
|
||||
go func() {
|
||||
for i := 10; i < 20; i++ {
|
||||
fmt.Print(i, " ")
|
||||
}
|
||||
}()
|
||||
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
28
ch09/syncGo.go
Normal file
28
ch09/syncGo.go
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
func main() {
|
||||
n := flag.Int("n", 20, "Number of goroutines")
|
||||
flag.Parse()
|
||||
count := *n
|
||||
fmt.Printf("Going to create %d goroutines.\n", count)
|
||||
|
||||
var waitGroup sync.WaitGroup
|
||||
fmt.Printf("%#v\n", waitGroup)
|
||||
for i := 0; i < count; i++ {
|
||||
waitGroup.Add(1)
|
||||
go func(x int) {
|
||||
defer waitGroup.Done()
|
||||
fmt.Printf("%d ", x)
|
||||
}(i)
|
||||
}
|
||||
|
||||
fmt.Printf("%#v\n", waitGroup)
|
||||
waitGroup.Wait()
|
||||
fmt.Println("\nExiting...")
|
||||
}
|
||||
19
ch09/writeCh.go
Normal file
19
ch09/writeCh.go
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func writeToChannel(c chan int, x int) {
|
||||
fmt.Println(x)
|
||||
c <- x
|
||||
close(c)
|
||||
fmt.Println(x)
|
||||
}
|
||||
|
||||
func main() {
|
||||
c := make(chan int)
|
||||
go writeToChannel(c, 10)
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
28
ch10/bufChannel.go
Normal file
28
ch10/bufChannel.go
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func main() {
|
||||
numbers := make(chan int, 5)
|
||||
counter := 10
|
||||
|
||||
for i := 0; i < counter; i++ {
|
||||
select {
|
||||
case numbers <- i:
|
||||
default:
|
||||
fmt.Println("Not enough space for", i)
|
||||
}
|
||||
}
|
||||
|
||||
for i := 0; i < counter+5; i++ {
|
||||
select {
|
||||
case num := <-numbers:
|
||||
fmt.Println(num)
|
||||
default:
|
||||
fmt.Println("Nothing more to be done!")
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
56
ch10/chSquare.go
Normal file
56
ch10/chSquare.go
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
var times int
|
||||
|
||||
func f1(cc chan chan int, f chan bool) {
|
||||
c := make(chan int)
|
||||
cc <- c
|
||||
defer close(c)
|
||||
|
||||
sum := 0
|
||||
select {
|
||||
case x := <-c:
|
||||
for i := 0; i <= x; i++ {
|
||||
sum = sum + i
|
||||
}
|
||||
c <- sum
|
||||
case <-f:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
arguments := os.Args
|
||||
if len(arguments) != 2 {
|
||||
fmt.Println("Need just one integer argument!")
|
||||
return
|
||||
}
|
||||
|
||||
times, err := strconv.Atoi(arguments[1])
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
cc := make(chan chan int)
|
||||
|
||||
for i := 1; i < times+1; i++ {
|
||||
f := make(chan bool)
|
||||
go f1(cc, f)
|
||||
ch := <-cc
|
||||
ch <- i
|
||||
for sum := range ch {
|
||||
fmt.Print("Sum(", i, ")=", sum)
|
||||
}
|
||||
fmt.Println()
|
||||
time.Sleep(time.Second)
|
||||
close(f)
|
||||
}
|
||||
}
|
||||
6
ch10/closeNilChannel.go
Normal file
6
ch10/closeNilChannel.go
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
package main
|
||||
|
||||
func main() {
|
||||
var c chan string
|
||||
close(c)
|
||||
}
|
||||
39
ch10/defineOrder.go
Normal file
39
ch10/defineOrder.go
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func A(a, b chan struct{}) {
|
||||
<-a
|
||||
fmt.Println("A()!")
|
||||
time.Sleep(time.Second)
|
||||
close(b)
|
||||
}
|
||||
|
||||
func B(a, b chan struct{}) {
|
||||
<-a
|
||||
fmt.Println("B()!")
|
||||
close(b)
|
||||
}
|
||||
|
||||
func C(a chan struct{}) {
|
||||
<-a
|
||||
fmt.Println("C()!")
|
||||
}
|
||||
|
||||
func main() {
|
||||
x := make(chan struct{})
|
||||
y := make(chan struct{})
|
||||
z := make(chan struct{})
|
||||
|
||||
go C(z)
|
||||
go A(x, y)
|
||||
go C(z)
|
||||
go B(y, z)
|
||||
go C(z)
|
||||
|
||||
close(x)
|
||||
time.Sleep(3 * time.Second)
|
||||
}
|
||||
31
ch10/forgetMutex.go
Normal file
31
ch10/forgetMutex.go
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var m sync.Mutex
|
||||
|
||||
func function() {
|
||||
m.Lock()
|
||||
fmt.Println("Locked!")
|
||||
}
|
||||
|
||||
func main() {
|
||||
var w sync.WaitGroup
|
||||
|
||||
go func() {
|
||||
defer w.Done()
|
||||
function()
|
||||
}()
|
||||
w.Add(1)
|
||||
|
||||
go func() {
|
||||
defer w.Done()
|
||||
function()
|
||||
}()
|
||||
w.Add(1)
|
||||
|
||||
w.Wait()
|
||||
}
|
||||
14
ch10/maxprocs.go
Normal file
14
ch10/maxprocs.go
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
func getGOMAXPROCS() int {
|
||||
return runtime.GOMAXPROCS(0)
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Printf("GOMAXPROCS: %d\n", getGOMAXPROCS())
|
||||
}
|
||||
60
ch10/monitor.go
Normal file
60
ch10/monitor.go
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var readValue = make(chan int)
|
||||
var writeValue = make(chan int)
|
||||
|
||||
func set(newValue int) {
|
||||
writeValue <- newValue
|
||||
}
|
||||
|
||||
func read() int {
|
||||
return <-readValue
|
||||
}
|
||||
|
||||
func monitor() {
|
||||
var value int
|
||||
for {
|
||||
select {
|
||||
case newValue := <-writeValue:
|
||||
value = newValue
|
||||
fmt.Printf("%d ", value)
|
||||
case readValue <- value:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 2 {
|
||||
fmt.Println("Please give an integer!")
|
||||
return
|
||||
}
|
||||
n, err := strconv.Atoi(os.Args[1])
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("Going to create %d random numbers.\n", n)
|
||||
rand.Seed(time.Now().Unix())
|
||||
go monitor()
|
||||
var w sync.WaitGroup
|
||||
|
||||
for r := 0; r < n; r++ {
|
||||
w.Add(1)
|
||||
go func() {
|
||||
defer w.Done()
|
||||
set(rand.Intn(10 * n))
|
||||
}()
|
||||
}
|
||||
w.Wait()
|
||||
fmt.Printf("\nLast value: %d\n", read())
|
||||
}
|
||||
58
ch10/mutex.go
Normal file
58
ch10/mutex.go
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
m sync.Mutex
|
||||
v1 int
|
||||
)
|
||||
|
||||
func change(i int) {
|
||||
m.Lock()
|
||||
time.Sleep(time.Second)
|
||||
v1 = v1 + 1
|
||||
if v1%10 == 0 {
|
||||
v1 = v1 - 10*i
|
||||
}
|
||||
m.Unlock()
|
||||
}
|
||||
|
||||
func read() int {
|
||||
m.Lock()
|
||||
a := v1
|
||||
m.Unlock()
|
||||
return a
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 2 {
|
||||
fmt.Println("Please give me an integer!")
|
||||
return
|
||||
}
|
||||
|
||||
numGR, err := strconv.Atoi(os.Args[1])
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
var waitGroup sync.WaitGroup
|
||||
|
||||
fmt.Printf("%d ", read())
|
||||
for i := 0; i < numGR; i++ {
|
||||
waitGroup.Add(1)
|
||||
go func(i int) {
|
||||
defer waitGroup.Done()
|
||||
change(i)
|
||||
fmt.Printf("-> %d", read())
|
||||
}(i)
|
||||
}
|
||||
|
||||
waitGroup.Wait()
|
||||
fmt.Printf("-> %d\n", read())
|
||||
}
|
||||
36
ch10/nilChannel.go
Normal file
36
ch10/nilChannel.go
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
func add(c chan int) {
|
||||
sum := 0
|
||||
t := time.NewTimer(time.Second)
|
||||
|
||||
for {
|
||||
select {
|
||||
case input := <-c:
|
||||
sum = sum + input
|
||||
case <-t.C:
|
||||
c = nil
|
||||
fmt.Println(sum)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func send(c chan int) {
|
||||
for {
|
||||
c <- rand.Intn(10)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
c := make(chan int)
|
||||
go add(c)
|
||||
go send(c)
|
||||
|
||||
time.Sleep(3 * time.Second)
|
||||
}
|
||||
43
ch10/noRaceC.go
Normal file
43
ch10/noRaceC.go
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var aMutex sync.Mutex
|
||||
|
||||
func main() {
|
||||
arguments := os.Args
|
||||
if len(arguments) != 2 {
|
||||
fmt.Println("Give me a natural number!")
|
||||
os.Exit(1)
|
||||
}
|
||||
numGR, err := strconv.Atoi(os.Args[1])
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
var waitGroup sync.WaitGroup
|
||||
var i int
|
||||
|
||||
k := make(map[int]int)
|
||||
k[1] = 12
|
||||
|
||||
for i = 0; i < numGR; i++ {
|
||||
waitGroup.Add(1)
|
||||
go func(j int) {
|
||||
defer waitGroup.Done()
|
||||
aMutex.Lock()
|
||||
k[j] = j
|
||||
aMutex.Unlock()
|
||||
}(i)
|
||||
}
|
||||
|
||||
waitGroup.Wait()
|
||||
k[2] = 10
|
||||
fmt.Printf("k = %#v\n", k)
|
||||
}
|
||||
39
ch10/raceC.go
Normal file
39
ch10/raceC.go
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
)
|
||||
|
||||
func main() {
|
||||
arguments := os.Args
|
||||
if len(arguments) != 2 {
|
||||
fmt.Println("Give me a natural number!")
|
||||
os.Exit(1)
|
||||
}
|
||||
numGR, err := strconv.Atoi(os.Args[1])
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
var waitGroup sync.WaitGroup
|
||||
var i int
|
||||
|
||||
k := make(map[int]int)
|
||||
k[1] = 12
|
||||
|
||||
for i = 0; i < numGR; i++ {
|
||||
waitGroup.Add(1)
|
||||
go func() {
|
||||
defer waitGroup.Done()
|
||||
k[i] = i
|
||||
}()
|
||||
}
|
||||
|
||||
k[2] = 10
|
||||
waitGroup.Wait()
|
||||
fmt.Printf("k = %#v\n", k)
|
||||
}
|
||||
70
ch10/rwMutex.go
Normal file
70
ch10/rwMutex.go
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var Password = secret{password: "myPassword"}
|
||||
|
||||
type secret struct {
|
||||
RWM sync.RWMutex
|
||||
password string
|
||||
}
|
||||
|
||||
func Change(c *secret, pass string) {
|
||||
c.RWM.Lock()
|
||||
fmt.Println("LChange")
|
||||
time.Sleep(10 * time.Second)
|
||||
c.password = pass
|
||||
c.RWM.Unlock()
|
||||
}
|
||||
|
||||
func show(c *secret) string {
|
||||
c.RWM.RLock()
|
||||
fmt.Print("show")
|
||||
time.Sleep(3 * time.Second)
|
||||
defer c.RWM.RUnlock()
|
||||
return c.password
|
||||
}
|
||||
|
||||
func showWithLock(c *secret) string {
|
||||
c.RWM.Lock()
|
||||
fmt.Println("showWithLock")
|
||||
time.Sleep(3 * time.Second)
|
||||
defer c.RWM.Unlock()
|
||||
return c.password
|
||||
}
|
||||
|
||||
func main() {
|
||||
var showFunction = func(c *secret) string { return "" }
|
||||
if len(os.Args) != 2 {
|
||||
fmt.Println("Using sync.RWMutex!")
|
||||
showFunction = show
|
||||
} else {
|
||||
fmt.Println("Using sync.Mutex!")
|
||||
showFunction = showWithLock
|
||||
}
|
||||
|
||||
var waitGroup sync.WaitGroup
|
||||
|
||||
fmt.Println("Pass:", showFunction(&Password))
|
||||
for i := 0; i < 15; i++ {
|
||||
waitGroup.Add(1)
|
||||
go func() {
|
||||
defer waitGroup.Done()
|
||||
fmt.Println("Go Pass:", showFunction(&Password))
|
||||
}()
|
||||
}
|
||||
|
||||
go func() {
|
||||
waitGroup.Add(1)
|
||||
defer waitGroup.Done()
|
||||
Change(&Password, "123456")
|
||||
}()
|
||||
|
||||
waitGroup.Wait()
|
||||
fmt.Println("Pass:", showFunction(&Password))
|
||||
}
|
||||
45
ch10/select.go
Normal file
45
ch10/select.go
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func gen(min, max int, createNumber chan int, end chan bool) {
|
||||
for {
|
||||
select {
|
||||
case createNumber <- rand.Intn(max-min) + min:
|
||||
case <-end:
|
||||
close(end)
|
||||
return
|
||||
case <-time.After(4 * time.Second):
|
||||
fmt.Println("\ntime.After()!")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
rand.Seed(time.Now().Unix())
|
||||
createNumber := make(chan int)
|
||||
end := make(chan bool)
|
||||
|
||||
if len(os.Args) != 2 {
|
||||
fmt.Println("Please give me an integer!")
|
||||
return
|
||||
}
|
||||
|
||||
n, _ := strconv.Atoi(os.Args[1])
|
||||
fmt.Printf("Going to create %d random numbers.\n", n)
|
||||
go gen(0, 2*n, createNumber, end)
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
fmt.Printf("%d ", <-createNumber)
|
||||
}
|
||||
|
||||
time.Sleep(5 * time.Second)
|
||||
fmt.Println("Exiting...")
|
||||
end <- true
|
||||
}
|
||||
88
ch10/simpleContext.go
Normal file
88
ch10/simpleContext.go
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func f1(t int) {
|
||||
c1 := context.Background()
|
||||
c1, cancel := context.WithCancel(c1)
|
||||
defer cancel()
|
||||
|
||||
go func() {
|
||||
time.Sleep(4 * time.Second)
|
||||
cancel()
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-c1.Done():
|
||||
fmt.Println("f1():", c1.Err())
|
||||
return
|
||||
case r := <-time.After(time.Duration(t) * time.Second):
|
||||
fmt.Println("f1():", r)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func f2(t int) {
|
||||
c2 := context.Background()
|
||||
c2, cancel := context.WithTimeout(c2, time.Duration(t)*time.Second)
|
||||
defer cancel()
|
||||
|
||||
go func() {
|
||||
time.Sleep(4 * time.Second)
|
||||
cancel()
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-c2.Done():
|
||||
fmt.Println("f2():", c2.Err())
|
||||
return
|
||||
case r := <-time.After(time.Duration(t) * time.Second):
|
||||
fmt.Println("f2():", r)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func f3(t int) {
|
||||
c3 := context.Background()
|
||||
deadline := time.Now().Add(time.Duration(2*t) * time.Second)
|
||||
c3, cancel := context.WithDeadline(c3, deadline)
|
||||
defer cancel()
|
||||
|
||||
go func() {
|
||||
time.Sleep(4 * time.Second)
|
||||
cancel()
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-c3.Done():
|
||||
fmt.Println("f3():", c3.Err())
|
||||
return
|
||||
case r := <-time.After(time.Duration(t) * time.Second):
|
||||
fmt.Println("f3():", r)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 2 {
|
||||
fmt.Println("Need a delay!")
|
||||
return
|
||||
}
|
||||
|
||||
delay, err := strconv.Atoi(os.Args[1])
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
fmt.Println("Delay:", delay)
|
||||
|
||||
f1(delay)
|
||||
f2(delay)
|
||||
f3(delay)
|
||||
}
|
||||
42
ch10/slowWWW.go
Normal file
42
ch10/slowWWW.go
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func random(min, max int) int {
|
||||
return rand.Intn(max-min) + min
|
||||
}
|
||||
|
||||
func myHandler(w http.ResponseWriter, r *http.Request) {
|
||||
delay := random(0, 15)
|
||||
time.Sleep(time.Duration(delay) * time.Second)
|
||||
|
||||
fmt.Fprintf(w, "Serving: %s\n", r.URL.Path)
|
||||
fmt.Fprintf(w, "Delay: %d\n", delay)
|
||||
fmt.Printf("Served: %s\n", r.Host)
|
||||
}
|
||||
|
||||
func main() {
|
||||
seed := time.Now().Unix()
|
||||
rand.Seed(seed)
|
||||
|
||||
PORT := ":8001"
|
||||
arguments := os.Args
|
||||
if len(arguments) == 1 {
|
||||
fmt.Println("Using default port number: ", PORT)
|
||||
} else {
|
||||
PORT = ":" + arguments[1]
|
||||
}
|
||||
|
||||
http.HandleFunc("/", myHandler)
|
||||
err := http.ListenAndServe(PORT, nil)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(10)
|
||||
}
|
||||
}
|
||||
34
ch10/timeOut1.go
Normal file
34
ch10/timeOut1.go
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
c1 := make(chan string)
|
||||
go func() {
|
||||
time.Sleep(time.Second * 3)
|
||||
c1 <- "c1 OK"
|
||||
}()
|
||||
|
||||
select {
|
||||
case res := <-c1:
|
||||
fmt.Println(res)
|
||||
case <-time.After(time.Second * 1):
|
||||
fmt.Println("timeout c1")
|
||||
}
|
||||
|
||||
c2 := make(chan string)
|
||||
go func() {
|
||||
time.Sleep(3 * time.Second)
|
||||
c2 <- "c2 OK"
|
||||
}()
|
||||
|
||||
select {
|
||||
case res := <-c2:
|
||||
fmt.Println(res)
|
||||
case <-time.After(4 * time.Second):
|
||||
fmt.Println("timeout c2")
|
||||
}
|
||||
}
|
||||
58
ch10/timeOut2.go
Normal file
58
ch10/timeOut2.go
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
func timeout(w *sync.WaitGroup, t time.Duration) bool {
|
||||
temp := make(chan int)
|
||||
go func() {
|
||||
time.Sleep(5 * time.Second)
|
||||
defer close(temp)
|
||||
w.Wait()
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-temp:
|
||||
return false
|
||||
case <-time.After(t):
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
arguments := os.Args
|
||||
if len(arguments) != 2 {
|
||||
fmt.Println("Need a time duration!")
|
||||
return
|
||||
}
|
||||
|
||||
var w sync.WaitGroup
|
||||
w.Add(1)
|
||||
|
||||
t, err := strconv.Atoi(arguments[1])
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
duration := time.Duration(int32(t)) * time.Millisecond
|
||||
fmt.Printf("Timeout period is %s\n", duration)
|
||||
|
||||
if timeout(&w, duration) {
|
||||
fmt.Println("Timed out!")
|
||||
} else {
|
||||
fmt.Println("OK!")
|
||||
}
|
||||
|
||||
w.Done()
|
||||
if timeout(&w, duration) {
|
||||
fmt.Println("Timed out!")
|
||||
} else {
|
||||
fmt.Println("OK!")
|
||||
}
|
||||
}
|
||||
98
ch10/useContext.go
Normal file
98
ch10/useContext.go
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
myUrl string
|
||||
delay int = 5
|
||||
w sync.WaitGroup
|
||||
)
|
||||
|
||||
type myData struct {
|
||||
r *http.Response
|
||||
err error
|
||||
}
|
||||
|
||||
func connect(c context.Context) error {
|
||||
defer w.Done()
|
||||
data := make(chan myData, 1)
|
||||
|
||||
tr := &http.Transport{}
|
||||
httpClient := &http.Client{Transport: tr}
|
||||
|
||||
req, _ := http.NewRequest("GET", myUrl, nil)
|
||||
|
||||
go func() {
|
||||
response, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
data <- myData{nil, err}
|
||||
return
|
||||
} else {
|
||||
pack := myData{response, err}
|
||||
data <- pack
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-c.Done():
|
||||
tr.CancelRequest(req)
|
||||
<-data
|
||||
fmt.Println("The request was cancelled!")
|
||||
return c.Err()
|
||||
case ok := <-data:
|
||||
err := ok.err
|
||||
resp := ok.r
|
||||
if err != nil {
|
||||
fmt.Println("Error select:", err)
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
realHTTPData, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
fmt.Println("Error select:", err)
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Server Response: %s\n", realHTTPData)
|
||||
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) == 1 {
|
||||
fmt.Println("Need a URL and a delay!")
|
||||
return
|
||||
}
|
||||
|
||||
myUrl = os.Args[1]
|
||||
if len(os.Args) == 3 {
|
||||
t, err := strconv.Atoi(os.Args[2])
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
delay = t
|
||||
}
|
||||
|
||||
fmt.Println("Delay:", delay)
|
||||
c := context.Background()
|
||||
c, cancel := context.WithTimeout(c, time.Duration(delay)*time.Second)
|
||||
defer cancel()
|
||||
|
||||
fmt.Printf("Connecting to %s \n", myUrl)
|
||||
w.Add(1)
|
||||
go connect(c)
|
||||
w.Wait()
|
||||
fmt.Println("Exiting...")
|
||||
}
|
||||
88
ch10/workerPool.go
Normal file
88
ch10/workerPool.go
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
id int
|
||||
integer int
|
||||
}
|
||||
|
||||
type Data struct {
|
||||
job Client
|
||||
square int
|
||||
}
|
||||
|
||||
var (
|
||||
size = 10
|
||||
clients = make(chan Client, size)
|
||||
data = make(chan Data, size)
|
||||
)
|
||||
|
||||
func worker(w *sync.WaitGroup) {
|
||||
for c := range clients {
|
||||
square := c.integer * c.integer
|
||||
output := Data{c, square}
|
||||
data <- output
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
w.Done()
|
||||
}
|
||||
|
||||
func makeWP(n int) {
|
||||
var w sync.WaitGroup
|
||||
for i := 0; i < n; i++ {
|
||||
w.Add(1)
|
||||
go worker(&w)
|
||||
}
|
||||
w.Wait()
|
||||
close(data)
|
||||
}
|
||||
|
||||
func create(n int) {
|
||||
for i := 0; i < n; i++ {
|
||||
c := Client{i, i}
|
||||
clients <- c
|
||||
}
|
||||
close(clients)
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println("Capacity of clients:", cap(clients))
|
||||
fmt.Println("Capacity of data:", cap(data))
|
||||
|
||||
if len(os.Args) != 3 {
|
||||
fmt.Println("Need #jobs and #workers!")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
nJobs, err := strconv.Atoi(os.Args[1])
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
nWorkers, err := strconv.Atoi(os.Args[2])
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
go create(nJobs)
|
||||
finished := make(chan interface{})
|
||||
go func() {
|
||||
for d := range data {
|
||||
fmt.Printf("Client ID: %d\tint: ", d.job.id)
|
||||
fmt.Printf("%d\tsquare: %d\n", d.job.integer, d.square)
|
||||
}
|
||||
finished <- true
|
||||
}()
|
||||
|
||||
makeWP(nWorkers)
|
||||
fmt.Printf(": %v\n", <-finished)
|
||||
}
|
||||
42
ch11/benchmarkMe.go
Normal file
42
ch11/benchmarkMe.go
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func fibo1(n int) int {
|
||||
if n == 0 {
|
||||
return 0
|
||||
} else if n == 1 {
|
||||
return 1
|
||||
} else {
|
||||
return fibo1(n-1) + fibo1(n-2)
|
||||
}
|
||||
}
|
||||
|
||||
func fibo2(n int) int {
|
||||
if n == 0 || n == 1 {
|
||||
return n
|
||||
}
|
||||
return fibo2(n-1) + fibo2(n-2)
|
||||
}
|
||||
|
||||
func fibo3(n int) int {
|
||||
fn := make(map[int]int)
|
||||
for i := 0; i <= n; i++ {
|
||||
var f int
|
||||
if i <= 2 {
|
||||
f = 1
|
||||
} else {
|
||||
f = fn[i-1] + fn[i-2]
|
||||
}
|
||||
fn[i] = f
|
||||
}
|
||||
return fn[n]
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println(fibo1(40))
|
||||
fmt.Println(fibo2(40))
|
||||
fmt.Println(fibo3(40))
|
||||
}
|
||||
81
ch11/benchmarkMe_test.go
Normal file
81
ch11/benchmarkMe_test.go
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
var result int
|
||||
|
||||
func benchmarkfibo1(b *testing.B, n int) {
|
||||
var r int
|
||||
for i := 0; i < b.N; i++ {
|
||||
r = fibo1(n)
|
||||
}
|
||||
result = r
|
||||
}
|
||||
|
||||
func benchmarkfibo2(b *testing.B, n int) {
|
||||
var r int
|
||||
for i := 0; i < b.N; i++ {
|
||||
r = fibo2(n)
|
||||
}
|
||||
result = r
|
||||
}
|
||||
|
||||
func benchmarkfibo3(b *testing.B, n int) {
|
||||
var r int
|
||||
for i := 0; i < b.N; i++ {
|
||||
r = fibo3(n)
|
||||
}
|
||||
result = r
|
||||
}
|
||||
|
||||
func Benchmark30fibo1(b *testing.B) {
|
||||
benchmarkfibo1(b, 30)
|
||||
}
|
||||
|
||||
func Benchmark30fibo2(b *testing.B) {
|
||||
benchmarkfibo2(b, 30)
|
||||
}
|
||||
|
||||
func Benchmark30fibo3(b *testing.B) {
|
||||
benchmarkfibo3(b, 30)
|
||||
}
|
||||
|
||||
func Benchmark50fibo1(b *testing.B) {
|
||||
benchmarkfibo1(b, 50)
|
||||
}
|
||||
|
||||
func Benchmark50fibo2(b *testing.B) {
|
||||
benchmarkfibo2(b, 50)
|
||||
}
|
||||
|
||||
func Benchmark50fibo3(b *testing.B) {
|
||||
benchmarkfibo3(b, 50)
|
||||
}
|
||||
|
||||
// This is a correct benchmark function
|
||||
func BenchmarkFiboIV(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = fibo3(10)
|
||||
}
|
||||
}
|
||||
|
||||
// This is also a correct benchmark function
|
||||
func BenchmarkFiboIII(b *testing.B) {
|
||||
_ = fibo3(b.N)
|
||||
}
|
||||
|
||||
// This benchmark function never converges
|
||||
// func BenchmarkFiboI(b *testing.B) {
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// _ = fibo1(i)
|
||||
// }
|
||||
// }
|
||||
|
||||
// This benchmark function never converges
|
||||
// func BenchmarkFiboII(b *testing.B) {
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// _ = fibo2(b.N)
|
||||
// }
|
||||
// }
|
||||
53
ch11/betterProfile.go
Normal file
53
ch11/betterProfile.go
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/pkg/profile"
|
||||
)
|
||||
|
||||
var VARIABLE int
|
||||
|
||||
func N1(n int) bool {
|
||||
for i := 2; i < n; i++ {
|
||||
if (n % i) == 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func Multiply(a, b int) int {
|
||||
if a == 1 {
|
||||
return b
|
||||
}
|
||||
if a == 0 || b == 0 {
|
||||
return 0
|
||||
}
|
||||
if a < 0 {
|
||||
return -Multiply(-a, b)
|
||||
}
|
||||
return b + Multiply(a-1, b)
|
||||
}
|
||||
|
||||
func main() {
|
||||
defer profile.Start(profile.ProfilePath("/tmp")).Stop()
|
||||
|
||||
total := 0
|
||||
for i := 2; i < 200000; i++ {
|
||||
n := N1(i)
|
||||
if n {
|
||||
total++
|
||||
}
|
||||
}
|
||||
fmt.Println("Total: ", total)
|
||||
|
||||
total = 0
|
||||
for i := 0; i < 5000; i++ {
|
||||
for j := 0; j < 400; j++ {
|
||||
k := Multiply(i, j)
|
||||
VARIABLE = k
|
||||
total++
|
||||
}
|
||||
}
|
||||
fmt.Println("Total: ", total)
|
||||
}
|
||||
25
ch11/cannotReach.go
Normal file
25
ch11/cannotReach.go
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func f1() int {
|
||||
fmt.Println("Entering f1()")
|
||||
// return -10
|
||||
fmt.Println("Exiting f1()")
|
||||
return -1
|
||||
}
|
||||
|
||||
func f2() int {
|
||||
if true {
|
||||
return 10
|
||||
}
|
||||
fmt.Println("Exiting f2()")
|
||||
return 0
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println(f1())
|
||||
fmt.Println("Exiting program...")
|
||||
}
|
||||
26
ch11/documentMe.go
Normal file
26
ch11/documentMe.go
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
// This package is for showcasing the documentation capabilities of Go
|
||||
// It is a naive package!
|
||||
package documentMe
|
||||
|
||||
// Pie is a global variable
|
||||
// This is a silly comment!
|
||||
const Pie = 3.1415912
|
||||
|
||||
// The S1() function finds the length of a string
|
||||
// It iterates over the string using range
|
||||
func S1(s string) int {
|
||||
if s == "" {
|
||||
return 0
|
||||
}
|
||||
n := 0
|
||||
for range s {
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// The F1() function returns the double value of its input integer
|
||||
// A better function name would have been Double()!
|
||||
func F1(n int) int {
|
||||
return 2 * n
|
||||
}
|
||||
21
ch11/documentMe_test.go
Normal file
21
ch11/documentMe_test.go
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
package documentMe
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func ExampleS1() {
|
||||
fmt.Println(S1("123456789"))
|
||||
fmt.Println(S1(""))
|
||||
// Output:
|
||||
// 9
|
||||
// 0
|
||||
}
|
||||
|
||||
func ExampleF1() {
|
||||
fmt.Println(F1(10))
|
||||
fmt.Println(F1(2))
|
||||
// Output:
|
||||
// 1
|
||||
// 55
|
||||
}
|
||||
15
ch11/ex.go
Normal file
15
ch11/ex.go
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
package ex
|
||||
|
||||
func F1(n int) int {
|
||||
if n == 0 {
|
||||
return 0
|
||||
}
|
||||
if n == 1 || n == 2 {
|
||||
return 1
|
||||
}
|
||||
return F1(n-1) + F1(n-2)
|
||||
}
|
||||
|
||||
func S1(s string) int {
|
||||
return len(s)
|
||||
}
|
||||
21
ch11/ex_test.go
Normal file
21
ch11/ex_test.go
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
package ex
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func ExampleF1() {
|
||||
fmt.Println(F1(10))
|
||||
fmt.Println(F1(2))
|
||||
// Output:
|
||||
// 55
|
||||
// 1
|
||||
}
|
||||
|
||||
func ExampleS1() {
|
||||
fmt.Println(S1("123456789"))
|
||||
fmt.Println(S1(""))
|
||||
// Output:
|
||||
// 8
|
||||
// 0
|
||||
}
|
||||
53
ch11/goGC.go
Normal file
53
ch11/goGC.go
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"runtime/trace"
|
||||
"time"
|
||||
)
|
||||
|
||||
func printStats(mem runtime.MemStats) {
|
||||
runtime.ReadMemStats(&mem)
|
||||
fmt.Println("mem.Alloc:", mem.Alloc)
|
||||
fmt.Println("mem.TotalAlloc:", mem.TotalAlloc)
|
||||
fmt.Println("mem.HeapAlloc:", mem.HeapAlloc)
|
||||
fmt.Println("mem.NumGC:", mem.NumGC)
|
||||
fmt.Println("-----")
|
||||
}
|
||||
|
||||
func main() {
|
||||
f, err := os.Create("/tmp/traceFile.out")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
err = trace.Start(f)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer trace.Stop()
|
||||
|
||||
var mem runtime.MemStats
|
||||
printStats(mem)
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
s := make([]byte, 50000000)
|
||||
if s == nil {
|
||||
fmt.Println("Operation failed!")
|
||||
}
|
||||
}
|
||||
printStats(mem)
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
s := make([]byte, 100000000)
|
||||
if s == nil {
|
||||
fmt.Println("Operation failed!")
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
printStats(mem)
|
||||
}
|
||||
24
ch11/graph.dot
Normal file
24
ch11/graph.dot
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
digraph G
|
||||
{
|
||||
graph [dpi = 300, bgcolor = "gray"];
|
||||
rankdir = LR;
|
||||
node [shape=record, width=.2, height=.2, color="white" ];
|
||||
|
||||
node0 [label = "<p0> | <p1> | <p2> | <p3> | <p4> | | ", height = 3];
|
||||
node[ width=2 ];
|
||||
node1 [label = "{<e> r0 | 123 | <p> }", color="gray" ];
|
||||
node2 [label = "{<e> r10 | 13 | <p> }" ];
|
||||
node3 [label = "{<e> r11 | 23 | <p> }" ];
|
||||
node4 [label = "{<e> r12 | 326 | <p> }" ];
|
||||
node5 [label = "{<e> r13 | 1f3 | <p> }" ];
|
||||
node6 [label = "{<e> r20 | 143 | <p> }" ];
|
||||
node7 [label = "{<e> r40 | b23 | <p> }" ];
|
||||
|
||||
node0:p0 -> node1:e [dir=both color="red:blue"];
|
||||
node0:p1 -> node2:e [dir=back arrowhead=diamond];
|
||||
node2:p -> node3:e;
|
||||
node3:p -> node4:e [dir=both arrowtail=box color="red"];
|
||||
node4:p -> node5:e [dir=forward];
|
||||
node0:p2 -> node6:e [dir=none color="orange"];
|
||||
node0:p4 -> node7:e;
|
||||
}
|
||||
116
ch11/profileMe.go
Normal file
116
ch11/profileMe.go
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"runtime"
|
||||
"runtime/pprof"
|
||||
"time"
|
||||
)
|
||||
|
||||
func fibo1(n int) int64 {
|
||||
if n == 0 || n == 1 {
|
||||
return int64(n)
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
return int64(fibo2(n-1)) + int64(fibo2(n-2))
|
||||
}
|
||||
|
||||
func fibo2(n int) int {
|
||||
fn := make(map[int]int)
|
||||
for i := 0; i <= n; i++ {
|
||||
var f int
|
||||
if i <= 2 {
|
||||
f = 1
|
||||
} else {
|
||||
f = fn[i-1] + fn[i-2]
|
||||
}
|
||||
fn[i] = f
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
return fn[n]
|
||||
}
|
||||
|
||||
func N1(n int) bool {
|
||||
k := math.Floor(float64(n/2 + 1))
|
||||
for i := 2; i < int(k); i++ {
|
||||
if (n % i) == 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func N2(n int) bool {
|
||||
for i := 2; i < n; i++ {
|
||||
if (n % i) == 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func main() {
|
||||
cpuFile, err := os.Create("/tmp/cpuProfile.out")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
pprof.StartCPUProfile(cpuFile)
|
||||
defer pprof.StopCPUProfile()
|
||||
|
||||
total := 0
|
||||
for i := 2; i < 100000; i++ {
|
||||
n := N1(i)
|
||||
if n {
|
||||
total = total + 1
|
||||
}
|
||||
}
|
||||
fmt.Println("Total primes:", total)
|
||||
|
||||
total = 0
|
||||
for i := 2; i < 100000; i++ {
|
||||
n := N2(i)
|
||||
if n {
|
||||
total = total + 1
|
||||
}
|
||||
}
|
||||
fmt.Println("Total primes:", total)
|
||||
|
||||
for i := 1; i < 90; i++ {
|
||||
n := fibo1(i)
|
||||
fmt.Print(n, " ")
|
||||
}
|
||||
fmt.Println()
|
||||
|
||||
for i := 1; i < 90; i++ {
|
||||
n := fibo2(i)
|
||||
fmt.Print(n, " ")
|
||||
}
|
||||
fmt.Println()
|
||||
|
||||
runtime.GC()
|
||||
|
||||
// Memory profiling!
|
||||
memory, err := os.Create("/tmp/memoryProfile.out")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer memory.Close()
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
s := make([]byte, 50000000)
|
||||
if s == nil {
|
||||
fmt.Println("Operation failed!")
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
|
||||
err = pprof.WriteHeapProfile(memory)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
37
ch11/testMe.go
Normal file
37
ch11/testMe.go
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
package testMe
|
||||
|
||||
func f1(n int) int {
|
||||
if n == 0 {
|
||||
return 0
|
||||
}
|
||||
if n == 1 {
|
||||
return 1
|
||||
}
|
||||
return f1(n-1) + f1(n-2)
|
||||
}
|
||||
|
||||
func f2(n int) int {
|
||||
if n == 0 {
|
||||
return 0
|
||||
}
|
||||
if n == 1 {
|
||||
return 2
|
||||
}
|
||||
|
||||
return f2(n-1) + f2(n-2)
|
||||
}
|
||||
|
||||
func s1(s string) int {
|
||||
if s == "" {
|
||||
return 0
|
||||
}
|
||||
n := 1
|
||||
for range s {
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func s2(s string) int {
|
||||
return len(s)
|
||||
}
|
||||
60
ch11/testMe_test.go
Normal file
60
ch11/testMe_test.go
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
package testMe
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestS1(t *testing.T) {
|
||||
if s1("123456789") != 9 {
|
||||
t.Error(`s1("123456789") != 9`)
|
||||
}
|
||||
|
||||
if s1("") != 0 {
|
||||
t.Error(`s1("") != 0`)
|
||||
}
|
||||
}
|
||||
|
||||
func TestS2(t *testing.T) {
|
||||
if s2("123456789") != 9 {
|
||||
t.Error(`s2("123456789") != 9`)
|
||||
}
|
||||
|
||||
if s2("") != 0 {
|
||||
t.Error(`s2("") != 0`)
|
||||
}
|
||||
}
|
||||
|
||||
func TestF1(t *testing.T) {
|
||||
if f1(0) != 0 {
|
||||
t.Error(`f1(0) != 0`)
|
||||
}
|
||||
|
||||
if f1(1) != 1 {
|
||||
t.Error(`f1(1) != 1`)
|
||||
}
|
||||
|
||||
if f1(2) != 1 {
|
||||
t.Error(`f1(2) != 1`)
|
||||
}
|
||||
|
||||
if f1(10) != 55 {
|
||||
t.Error(`f1(10) != 55`)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestF2(t *testing.T) {
|
||||
if f2(0) != 0 {
|
||||
t.Error(`f2(0) != 0`)
|
||||
}
|
||||
|
||||
if f2(1) != 1 {
|
||||
t.Error(`f2(1) != 1`)
|
||||
}
|
||||
|
||||
if f2(2) != 1 {
|
||||
t.Error(`f2(2) != 1`)
|
||||
}
|
||||
|
||||
if f2(10) != 55 {
|
||||
t.Error(`f2(10) != 55`)
|
||||
}
|
||||
}
|
||||
82
ch11/writingBU.go
Normal file
82
ch11/writingBU.go
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
var BUFFERSIZE int
|
||||
var FILESIZE int
|
||||
|
||||
func random(min, max int) int {
|
||||
return rand.Intn(max-min) + min
|
||||
}
|
||||
|
||||
func createBuffer(buf *[]byte, count int) {
|
||||
*buf = make([]byte, count)
|
||||
if count == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
for i := 0; i < count; i++ {
|
||||
intByte := byte(random(0, 100))
|
||||
if len(*buf) > count {
|
||||
return
|
||||
}
|
||||
*buf = append(*buf, intByte)
|
||||
}
|
||||
}
|
||||
|
||||
func Create(dst string, b, f int) error {
|
||||
_, err := os.Stat(dst)
|
||||
if err == nil {
|
||||
return fmt.Errorf("File %s already exists.", dst)
|
||||
}
|
||||
|
||||
destination, err := os.Create(dst)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer destination.Close()
|
||||
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
buf := make([]byte, 0)
|
||||
for {
|
||||
createBuffer(&buf, b)
|
||||
buf = buf[:b]
|
||||
if _, err := destination.Write(buf); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if f < 0 {
|
||||
break
|
||||
}
|
||||
f = f - len(buf)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 3 {
|
||||
fmt.Println("Need BUFFERSIZE FILESIZE!")
|
||||
return
|
||||
}
|
||||
|
||||
output := "/tmp/randomFile"
|
||||
BUFFERSIZE, _ = strconv.Atoi(os.Args[1])
|
||||
FILESIZE, _ = strconv.Atoi(os.Args[2])
|
||||
err := Create(output, BUFFERSIZE, FILESIZE)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
|
||||
err = os.Remove(output)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue