天涯海角异孤星
Go 接收任意数量参数的函数,使用了 ...type
语法糖:
package main
import "fmt"
func MyPrintf(args ...interface{}) {
for _, arg := range args {
switch arg.(type) {
case int:
fmt.Println(arg, "is an int value.")
case string:
fmt.Println(arg, "is an string value.")
case int64:
fmt.Println(arg, "is an int64 value.")
default:
fmt.Println(arg, "is an unknow type.")
}
}
}
func main() {
var v1 int = 1
var v2 int64 = 234
var v3 string = "hello"
var v4 float32 = 1.234
MyPrintf(v1, v2, v3, v4)
}
Go 计算文件的 md5 和 sha1:
package main
import (
"crypto/md5"
"crypto/sha1"
"fmt"
"io"
"os"
)
func main() {
TestFile := "123.txt"
infile, inerr := os.Open(TestFile)
if inerr == nil {
md5h := md5.New()
io.Copy(md5h, infile)
fmt.Printf("%x %s\n", md5h.Sum([]byte("")), TestFile)
// 前面计算md5后,文件读写位置变了,这里调用Seek重置起始位置
infile.Seek(0, 0)
sha1h := sha1.New()
io.Copy(sha1h, infile)
fmt.Printf("%x %s\n", sha1h.Sum([]byte("")), TestFile)
} else {
fmt.Println(inerr)
os.Exit(1)
}
}
Go 计算字符串的 md5 和 sha1:
package main
import (
"crypto/md5"
"crypto/sha1"
"fmt"
)
func main() {
TestString := "Hi, pandaman!"
Md5Inst := md5.New()
Md5Inst.Write([]byte(TestString))
Result := Md5Inst.Sum([]byte(""))
fmt.Printf("%x\n\n", Result)
Sha1Inst := sha1.New()
Sha1Inst.Write([]byte(TestString))
Result = Sha1Inst.Sum([]byte(""))
fmt.Printf("%x\n\n", Result)
}
Go 语言中的 map 示例(key-value 键值对) :
package main
import "fmt"
type PersonInfo struct {
ID string
Name string
Address string
}
func main() {
var persionDB map[string]PersonInfo
persionDB = make(map[string]PersonInfo)
persionDB["1234"] = PersonInfo{"12345", "Tom", "Room 203,..."}
persionDB["1"] = PersonInfo{"1", "Jack", "Room 101,..."}
person, ok := persionDB["1234"]
if ok {
fmt.Println("Found person", person.Name, "with ID 1234.")
} else {
fmt.Println("Did not find person with ID 1234.")
}
}