Created
November 13, 2018 07:18
-
-
Save harryhare/1dff07944b5ad10676ad6a744b640ece to your computer and use it in GitHub Desktop.
用interface 传递slice指针作为函数参数,并填充
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const maxIdle = 2 | |
const address = "127.0.0.1:6379" | |
var pool = redis.Pool{ | |
MaxIdle: maxIdle, | |
Dial: func() (redis.Conn, error) { | |
return redis.Dial("tcp", address) | |
}, | |
TestOnBorrow: func(c redis.Conn, t time.Time) error { | |
_, err := c.Do("PING") | |
return err | |
}, | |
} | |
func getbatch(keys []string, values interface{}) { | |
c := pool.Get() | |
defer c.Close() | |
resultv := reflect.ValueOf(values) | |
slicev := resultv.Elem() | |
slicev = slicev.Slice(0, slicev.Cap()) | |
elemt := slicev.Type().Elem() | |
for _, key := range keys { | |
e := c.Send("get", key) | |
if e != nil { | |
panic(e) | |
} | |
} | |
c.Flush() | |
for _ = range keys { | |
elemp := reflect.New(elemt) | |
b, e := c.Receive() | |
if e != nil { | |
panic(e) | |
} | |
e=json.Unmarshal(b.([]byte), elemp.Interface()) | |
if e!=nil{ | |
panic(e) | |
} | |
slicev = reflect.Append(slicev, elemp.Elem()) | |
slicev = slicev.Slice(0, slicev.Cap()) | |
} | |
resultv.Elem().Set(slicev.Slice(0, len(keys))) | |
} | |
type AAAA struct{ | |
Value string | |
} | |
func set(key string, value string){ | |
c:=pool.Get() | |
defer c.Close() | |
v1:=&AAAA{Value:value} | |
b,e:=json.Marshal(v1) | |
if e!=nil{ | |
panic(e) | |
} | |
c.Do("set",key,string(b)) | |
} | |
// slice 一定要有* | |
func test000(ss *[]string) { | |
*ss = append(*ss, "1") | |
*ss = append(*ss, "2") | |
} | |
func test002(mm map[string]string) { | |
mm["a"] = "aa" | |
mm["b"] = "bb" | |
} | |
func main() { | |
set("struct001","001") | |
set("struct002","002") | |
keys:=[]string{"struct001","struct002"} | |
values:=[]*AAAA{} | |
//values:=[]AAAA{} | |
getbatch(keys,&values) | |
for _,value:=range values{ | |
fmt.Println(value) | |
} | |
ss := []string{} | |
test000(&ss) | |
fmt.Println(ss) | |
mm:=map[string]string{} | |
test002(mm) | |
fmt.Println(mm) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment