golang编程技巧

高效的字符串追加 var buffer bytes.Buffer
for {
if piece, ok := getNextVaildString(); ok {
buffer.WriteString(piece)
} else {
break
}
}
fmt.Print(buffer.String(), “\n”) 纯记忆函数 type memozieFunction func(int, …int) interface{}
var Fibonacci memozieFunction

func Memoize(function memozieFunction) memozieFunction {
cache := make(map[string]interface{})
return func(x int, xs …int) interface{} {
key := fmt.Sprint(x)
}
if value, found := cache[key]; found {
return value
}
value := function(x, xs…)
cache[key] = value
return value
}

func init() {
Fibonacci = Memoize(func(x int, xs …int) interface{} {
if x < 2 { return x } return Fibonacci(x-1).(int) + Fibonacci(x-2).(int) }) Fibonacci(45) Fibonacci(45) Fibonacci(45) } sort.Sort()实现结构体列表排序 type Entry struct { key string value string } type Entries []Entry func (entries Entries) Len() int { return len(entries) } func (entries Entries) Less(i, j int) bool { return entries[i].key < entries[j].key } func (entries Entries) Swap(i, j int) { entries[i], entries[j] = entries[j], entries[i] } func init() { ... ... result := sort.Sort(entries_value) }




欢迎投稿 职场/创业方向. 邮箱wangfzcom(AT)163.com:王夫子社区 » golang编程技巧

    标签:

点评 0

评论前必须登录!

登陆 注册