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/

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