Skip to content

Instantly share code, notes, and snippets.

@alsotang
Created July 11, 2012 18:51
Show Gist options
  • Save alsotang/3092344 to your computer and use it in GitHub Desktop.
Save alsotang/3092344 to your computer and use it in GitHub Desktop.
for KC
package main
import "fmt"
func main() {
v := []int{1,2,3,4,5,6,7,8}
mv := new(MeanValue)
/*mvFunc := mv.exec()*/
nmv := new(MeanValue)
nmvFunc := nmv.exec()
for i := range v {
nmvFunc(i)
}
fmt.Println(mv.value())
fmt.Println(nmv.value())
}
type MeanValue struct {
//go里面的各种类型都有个初始的零值,所以如你所愿,以下两个变量都会自动初始化为0
m_value, m_num int
}
func (mv *MeanValue) exec() func(int) {
return (func(ele int) {
mv.m_value += ele
mv.m_num++
})
}
func (mv *MeanValue) value() float64 {
fmt.Printf("m_value is %s, m_num is %s.\n", mv.m_value, mv.m_num)
return float64(mv.m_value)/float64(mv.m_num)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment