[TOC] ## 接口 用来存放简单的全局变量,并且是线性安全 ### expvar.NewInt() /expvar.NewFloat() ``` name := expvar.NewInt("name") name.Set(456) name.Add(123) //456+123 name.String() //"579" name.Value() //579 ``` ### expvar.NewString() ``` newString := expvar.NewString("test") newString.Set("hello") fmt.Println(newString.Value()) ``` ### expvar.NewMap() ``` newmap := expvar.NewMap("map") newmap.Add("red", 1) newmap.Add("red", 2) //1+2 newmap.Add("blue", 4) newmap.AddFloat(`green "midori"`, 4.125) newmap.AddFloat(`green "midori"`, 0.01) //4.125+0.01 fmt.Println(newmap.Get("red")) //3 fmt.Println(newmap.Get(`green "midori"`)) //4.135 newmap.Delete("blue") fmt.Println(newmap.String()) //{"green \"midori\"": 4.135, "red": 3} newmap.Do(func(v expvar.KeyValue) { //遍历所有key 与value fmt.Println(v.Value) fmt.Println(v.Key) }) newmap.Init() //删除所有存储的值 ``` ### 通过访问`/debug/vars` 接口可以打印所有的值 ``` var visits = expvar.NewInt("visits") var ex_string = expvar.NewString("ex_string") func handler(w http.ResponseWriter, r *http.Request) { //添加值 visits.Add(1) log.Println(visits.Value()) //获取值 ex_string.Set("dmeo3") log.Println(ex_string.Value()) //demo3 log.Println("bists") fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) } ```