A Tour of Go 筆記

A Tour of Go
中文版
(方法部分看完,并發沒看)

一部分內容在無聞視頻中講解過了,筆記戳這里
大神寫的練習解答,戳這里

Packages

  1. the package name is the same as the last element of the import path. For instance, the "math/rand" package comprises files that begin with the statement package rand.

引用如果是“name1/name2”形式,包名是name2

示例程序中是rand.Intn(10),輸出1,每次輸出不變,因為環境是確定的,如果想要不同輸出,要用 rand.Seed
.鏈接里有解釋,(If Seed is not called, the generator behaves as if seeded by Seed(1).)

Import

import (
    "fmt"
    "math"
)

Exported names

可見性原則
要使用 引入包中的參數,肯定是大寫,不然是不能引用的
比如:math.pi ×,math.Pi √

Functions

可以一個參數或多個參數,參數名在前,類型災后

Basic types

package main

import (
    "fmt"
    "math/cmplx"
)

var (
    ToBe   bool       = false
    MaxInt uint64     = 1<<64 - 1
    z      complex128 = cmplx.Sqrt(-5 + 12i)
)

func main() {
    const f = "%T(%v)\n"
    fmt.Printf(f, ToBe, ToBe)
    fmt.Printf(f, MaxInt, MaxInt)
    fmt.Printf(f, z, z)
}

//output:bool(false)
//uint64(18446744073709551615)
//complex128((2+3i))

輸出結果的地方注意:輸出類型,值

for

無聞視頻中講過,補充一點
死循環的實現在go里也非常簡單

func main() {
    for {
    }
}

IF FOR 練習

牛頓法開平方(以前好像在知乎上看到過一個人說自己的面試經歷,面試一家大公司,問了開平方,他講了牛頓法,結果面試官不知道是啥,然后他就很詳細的講解了牛頓法,但是我找不到那段話了,不然可以放過來,如果有人也見過可以私我)
簡單來說就是,比如開平方x,隨便猜一個結果a,a+x/2得出新的結果,每次都這樣算,得出的新結果會非常接近正確答案

package main

import (
    "fmt"
    "math"
)

func Sqrt(x float64) float64 {
    z := 1.0
    for {
        tmp := z - (z*z-x)/(2*z)
        fmt.Println(tmp)
        if tmp == z || math.Abs(tmp-z) < 0.000000000001 {
            break
        }
        z = tmp
    }
    return z
}

func main() {
    fmt.Println(Sqrt(2.0))
    fmt.Println(math.Sqrt(2.0))
}

Switch

Switch without a condition is the same as switch true.

Struct

  1. Struct fields are accessed using a dot.

  2. Struct fields can be accessed through a struct pointer.
    注意!To access the field X of a struct when we have the struct pointer p we could write(p).X. However, that notation is cumbersome, so the language permits us instead to write just p.X, without the explicit dereference.*

  3. 結構體,可以不加*,就是不用解引用

  4. Struct Literals字面量賦值方式

type Vertex struct {
    X, Y int
}

var (
    v1 = Vertex{1, 2}  // has type Vertex
    v2 = Vertex{X: 1}  // Y:0 is implicit
)

Slice

數組和slice的區別是聲明的時候[]中有沒有規定大小!

s := []struct {  //匿名結構體,
        i int
        b bool
    }{
//這里是slice 字面量賦值
        {2, true},
        {3, false},
        {5, true},
        {7, true},
        {11, false},
        {13, true},
    }
    fmt.Println(s)
func main() {
    var s []int
    printSlice(s)

    // append works on nil slices.
    s = append(s, 0)
    printSlice(s)

    // The slice grows as needed.
    s = append(s, 1)
    printSlice(s)

    // We can add more than one element at a time.
    //注意這里,擴容,之前cap=2,不夠,所以cap=2*2=4, 還是不夠, cap繼續擴容=4*2=8
    s = append(s, 2, 3, 4)
    printSlice(s)
}

func printSlice(s []int) {
    fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

//輸出
len=0 cap=0 []
len=1 cap=2 [0]
len=2 cap=2 [0 1]
len=5 cap=8 [0 1 2 3 4]

Range

package main

import "fmt"

var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}

func main() {
    for i, v := range pow {
        fmt.Printf("2**%d = %d\n", i, v)
    }
}

一個經典例子,當初我查range的時候到處都是這個例子,還有一點提一下,返回值想舍棄的時候用_

exercise:Slice

注意:slice內部的slice要單獨聲明

package main

import "golang.org/x/tour/pic"

func Pic(dx, dy int) [][]uint8 {
    picture := make([][]uint8, dy)
    for i := 0; i < dy; i++ {
    //注意這里,slice內部的slice要單獨聲明
        picture[i] = make([]uint8,dx)
        for j := 0; j < dx; j++ {
            picture[i][j] = uint8((dx + dy) / 2)
        }
    }
    return picture
}

func main() {
    pic.Show(Pic)
}

Maps

//初始化
m := make(map[string]int)
//賦值
m["Answer"] = 42
//多返回值,ok,用來判斷該key對應的有沒有value值,返回bool
v, ok := m["Answer"]
fmt.Println("The value:", v, "Present?", ok)

map exercise

package main

import (
    "golang.org/x/tour/wc"
    "strings"
    "fmt"
)

func WordCount(s string) map[string]int {
    counter := make(map[string]int)
    arr := strings.Fields(s)
    for _, val := range arr {
        counter[val]++
        fmt.Println(counter[val],val)
    }

    return counter
}

func main() {
    wc.Test(WordCount)
}

閉包、closures

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),
        )
    }
}

輸出:
0 0
1 -2
3 -6
6 -12
10 -20
15 -30
21 -42
28 -56
36 -72
45 -90

readers

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,string(b))
        fmt.Printf("b[:n] = %q\n", b[:n])
        if err == io.EOF {
            break
        }
    }
}

output;
n = 8 err = <nil> b = [72 101 108 108 111 44 32 82]
%!(EXTRA string=Hello, R)b[:n] = "Hello, R"
n = 6 err = <nil> b = [101 97 100 101 114 33 32 82]
%!(EXTRA string=eader! R)b[:n] = "eader!"
n = 0 err = EOF b = [101 97 100 101 114 33 32 82]
%!(EXTRA string=eader! R)b[:n] = ""
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容