I have Problem in Struct using Go.
example code:
package main
import (
"fmt"
)
type KeyVal struct {
Key interface{}
Value interface{}
}
type KeyVals []KeyVal
func (kvs *KeyVals) AddOld(key interface{}, val interface{}) {
kv := KeyVal{key, val,typ}
*kvs = append(*kvs, kv)
}
func (kvs *KeyVals) Add(key interface{}, val interface{}){
var flag,id = kvs.Exist(key)
if flag == true {
//kv := KeyVal{key,"Updated!"}
//*kvs=append(*kvs,kv)
//fmt.Println(*kvs[0].Key)
//update value of them
kv := KeyVal{key,val}
kvs[id]=kv
//*kvs[id]=kv
//fmt.Println("old set with id =",id,",","value =",kvs)
}else{
kv := KeyVal{key, val}
*kvs = append(*kvs, kv)
}
}
func (kvs *KeyVals) Search(skey interface{}) (bool,interface{},interface{}) {
for n, kv := range *kvs {
key := kv.Key
val := kv.Value
if(key == skey){
return true,n,val
}
}
return false,nil,nil
}
func (kvs *KeyVals) Exist(skey interface{})(bool,int) {
for n, kv := range *kvs {
key := kv.Key
if(key == skey){
return true,n
}
}
return false,-1
}
func main() {
var kvs keyval.KeyVals
kvs.Add("key1","value1")
kvs.Add("key2","value2")
kvs.Add("key3","value3")
kvs.Add("key4",5)
kvs.Add("key5",5.2)
kvs.Add("key5","new....")//this should update value of this key. but not work!
var flag,id,value = kvs.Search("key5")
fmt.Println(flag,id,value)
for _, kv := range kvs {
key := kv.Key
val := kv.Value
fmt.Println("", key," ==> ", val)
}
}
Problem of me:
in function Add() ,
kvs[id]=kv
have error! how fix?speed of
Exist()
andSearch()
is good? can not make better?I try add index name to code :
type KeyVals []KeyVal
change to : mean :type KeyVals [interface{}]KeyVal
ortype KeyVals [string]KeyVal
... but error!