golang 學習隨筆

1、big.Int

type Int struct {
	neg bool // sign 值小於0 爲 ture , 否則爲 false ,詳見 SetInt64 源碼   
	abs nat  // absolute value of the integer 所存值的絕對值
}

// SetInt64 sets z to x and returns z.
func (z *Int) SetInt64(x int64) *Int {
	neg := false
	if x < 0 {
		neg = true
		x = -x
	}
	z.abs = z.abs.setUint64(uint64(x))
	z.neg = neg
	return z
}

What is deserialize and serialize in JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

When transmitting data or storing them in a file, the data are required to be byte strings, but complex objects are seldom in this format. Serialization can convert these complex objects into byte strings for such use. After the byte strings are transmitted, the receiver will have to recover the original object from the byte string. This is known as deserialization.

Say, you have an object:

{foo: [1, 4, 7, 10], bar: "baz"}

serializing into JSON will convert it into a string:

'{"foo":[1,4,7,10],"bar":"baz"}'

which can be stored or sent through wire to anywhere. The receiver can then deserialize this string to get back the original object. {foo: [1, 4, 7, 10], bar: "baz"}.

stackoverflow:https://stackoverflow.com/questions/3316762/what-is-deserialize-and-serialize-in-json


2、math / rand 產生隨機數

    golang 中產生隨機數的代碼爲:

package main
import (
	"fmt"
	"math/rand"
)

func main() {
	fmt.Println(rand.Intn(10))  // 產生 [0,10) 範圍內的隨機數
}

       結果發現每次運行的結果都一樣,查了一下發現需要每次設置不同隨機數種子,產生的隨機數纔會不一樣。建議用獲取當前時間的方法做隨機數種子,這樣每次隨機數就不一樣。

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano()) // 當前時間作爲隨機種子
	fmt.Println(rand.Intn(10))  // 產生 [0,10) 範圍內的隨機數
}

雜項筆記

函數體外無法用 := 定義聲明,常量也無法用 := 聲明

同一個文件夾下只能用一個 main 函數 

while 循環:golang 的 while 循環

sum := 1
for sum < 100 {
    sum += sum
}
fmt.Println(sum)

無限循環

for {
    // to do something
}

if - else 語句:通 for 一樣,if 語句可以在條件執行前執行一個簡單的語句

if v := math.Pow(x, n); V < 100 {
    // to do somethin
}

 switch 語句:Go 只運行選定的 case,而非之後所有的 case。 實際上,Go 自動提供了在這些語言中每個 case 後面所需的 break 語句。 除非以 fallthrough 語句結束,否則分支會自動終止。 Go 的另一點重要的不同在於 switch 的 case 無需爲常量,可以是 func,且取值不必爲整數。可以在條件執行前執行一個簡單的語句。

func num2() int {
	return 2
}

...
...

switch a := 1; a {
case 1:
	fmt.Println(1)
	fallthrough
case num2():
	fmt.Println(2)
	fallthrough
case 3:
	fmt.Println(3)
default:
	fmt.Println("default")
}

switch 多個條件並列

for i := 0; i < 7; i++ {
	switch i {
	case 1, 2, 3, 4, 5, 6, 7:
		fmt.Println(i)
	}
}

 

switch 還能進行類型選擇

package main
import "fmt"
func do(i interface{}) {
	switch v := i.(type) {
	case int:
		fmt.Printf("Twice %v is %v\n", v, v*2)
	case string:
		fmt.Printf("%q is %v bytes long\n", v, len(v))
	default:
		fmt.Printf("I don't know about type %T!\n", v)
	}
}
func main() {
	do(21)
	do("hello")
	do(true)
}

 也可以無條件,沒有條件的 switch 同 switch true 一樣。這種形式能將一長串 if-then-else 寫得更加清晰。

t := time.Now()
switch {
case t.Hour() < 12:
	fmt.Println("Good morning!")
case t.Hour() < 17:
	fmt.Println("Good afternoon.")
default:
	fmt.Println("Good evening.")
}

       切片並不存儲任何數據,它只是描述了底層數組中的一段。更改切片的元素會修改其底層數組中對應的元素。與它共享底層數組的切片都會觀測到這些修改。切片擁有 長度 和 容量。切片的長度就是它所包含的元素個數。切片的容量是從它的第一個元素開始數,到其底層數組元素末尾的個數。切片 s 的長度和容量可通過表達式 len(s) 和 cap(s) 來獲取。切片的零值爲 nil 。

       可以用 make 動態創建切片 eg:  b := make([]int, 0, 5) // len(b)=0, cap(b)=5

package main
import "fmt"
func main() {
	names := [4]string{
		"John",
		"Paul",
		"George",
		"Ringo",
	}
	
	a := names[1:3]
	fmt.Println(a)
	a[0] = "XXX"       // 更改 a[0] 位置的值
	fmt.Println(a)     // a[0] 位置的值改變
	fmt.Println(names) // names[1] 位置的值跟着改變
}

函數傳函數,函數值也是值。它們可以向其他值一樣被傳遞或者被返回。

package main
import "fmt"

//                      函數作爲函數值          函數作爲返回值
func funcAddPlus (x int,y func(int, int) int) func(int) {
	fmt.Println(x + y(2, 3))

	result := func(res int) {
		fmt.Println(res)
	}
	return result
}
func main() {
	funcAdd := func(x, y int) int {
		return x + y
	}
	// 函數傳傳函數  返回函數再傳入3
	funcAddPlus(1, funcAdd)(3)
}

輸出:
6
3

類似 Java toStrin() 方法的 String() 接口,fmt 包中定義的 Stringer 是最普遍的接口之一。

type Stringer interface {
    String() string
}

Stringer 是一個可以用字符串描述自己的類型。fmt 包(還有很多包)都通過此接口來打印值。

package main
import "fmt"
type Person struct {
	Name string
	Age  int
}
func (p Person) String() string {
	return fmt.Sprintf("%v (%v years)", p.Name, p.Age)
}
func main() {
	a := Person{"Arthur Dent", 42}
	z := Person{"Zaphod Beeblebrox", 9001}
	fmt.Println(a) // 直接輸出 a, z 對象
    fmt.Println(z)
}

輸出:
Arthur Dent (42 years) 
Zaphod Beeblebrox (9001 years)

 


用如果該變量是全局變量 a,在所以調用該全局變量 a 的方法中不要用 a := 的方法定義,不然在該方法中會創建該全局變量 a 的局部變量 a ,局部變量 a 會屏蔽全局變量 a。


安裝 crypto/ripemd160 庫報錯

錯誤輸出:

package golang.org/x/crypto/ripemd160: unrecognized import path "golang.org/x/crypto/ripemd160" (https fetch: Get https://golang.org/x/crypto/ripemd160?go-get=1: dial tcp 216.239.37.1:443: i/o timeout)

發現連接無法訪問,可能是被牆了。golang 語言本身是開源的,在github能找到源碼庫。輸入以下命令即可下載源碼安裝。

mkdir -p $GOPATH/src/golang.org/x/
cd $GOPATH/src/golang.org/x/
git clone https://github.com/golang/crypto.git crypto
go install crypto

轉載:http://www.01happy.com/golang-go-get-golang-org-timeout/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章