go basic

时间:2023-03-08 20:49:31

go time and rand:

package main

import (
"fmt"
"math/rand"
"time"
) func main() {
rand.Seed(time.Now().Unix())
fmt.Println("My favorite number is :", rand.Int()%20)
}

get the runtime os:

package main

import (
"fmt"
"runtime"
) func main() {
fmt.Println("Go runs on")
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("os x")
case "linux":
fmt.Println("Linux.")
default:
fmt.Println("windows")
}
}

slice operator

package main

import (
"fmt"
// "reflect"
) func printSlice(s string, x []int) {
fmt.Printf("%s len=%d cap=%d %v\n", s, len(x), cap(x), x)
}
func main() {
var a []int
printSlice("a", a) //append works on nil slice
a = append(a, 0)
printSlice("a", a) a = append(a, 2, 3, 4)
printSlice("a", a) }

wordcount:

package main

import (
"fmt"
) func WordCount(s string) map[string]int {
// c := make(map[string]int)
c := map[string]int{}
b := []byte(s)
for _, v := range b {
fmt.Println(string(v))
if cap, ok := c[string(v)]; ok {
c[string(v)] = 1 + cap
} else {
c[string(v)] = 1
}
}
return c
} func main() {
a := WordCount("wwwcmome")
fmt.Println(a)
b := map[string]int{
"name": 20,
"age": 30,
}
b["work"] = 100
if cap, ok := b["name1"]; ok {
fmt.Println(cap)
} else {
fmt.Println("nothing")
}
fmt.Println(b)
}

闭包

package main

import "fmt"

func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
} func main() {
pos, neg := adder(), adder()
for i := 0; i < 10; i++ {
fmt.Println(
pos(i),
neg(-2*i),
)
}
}

check pointer

package main

import (
"fmt"
"math"
) type Abser interface {
Abs() float64
} type MyFloat float64 func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
} type Vertex struct {
x, y float64
} func (v *Vertex) Abs() float64 {
return math.Sqrt(v.x*v.x + v.y*v.y)
} func main() {
var a Abser
f := MyFloat(-math.Sqrt2)
v := Vertex{3, 4}
a = f
a = &v
fmt.Println(a.Abs())
}

strings.NewReader

package main

import (
"fmt"
"io"
"strings"
) func main() {
r := strings.NewReader("hello, Reader")
b := make([]byte, 8) for {
n, err := r.Read(b)
fmt.Printf("n=%v err=%v b=%v\n", n, err, b)
fmt.Printf("b[:n] = %q\n", b[:n])
if err == io.EOF {
break
}
}
}

use golang regexp

package main

import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
// "strings"
// "reflect"
) func main() {
resp, err := http.Get("http://www.163.com/")
if err != nil {
fmt.Println("http get error")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("http read error")
return
}
// fmt.Println(reflect.TypeOf(body))
src := string(body)
re, _ := regexp.Compile("http://[[:word:]]+.[[:word:]]+.com")
sslice := re.FindAllString(src, 1024)
for k, v := range removeReplaceSliceContent(sslice) {
fmt.Printf("%30s \t %5d\n", k, v)
}
} func removeReplaceSliceContent(s []string) map[string]int {
b := map[string]int{}
for _, v := range s {
b[v] += 1
}
return b
}