我正在学习 Golang,Google 把我带到了这里。一种方法是创建一个 DataStore 结构。我想出了这个[见这里][1]。如果这是一个好方法,请告诉我。
import (
"fmt"
)
type Data struct {
key string
value string
}
type DataStore struct {
datastore map[string]Data
}
func newDataStore() DataStore {
return DataStore{make(map[string]Data)}
}
/*
Puts the key and value in the DataStore.
If the key (k) already exists will replace with the provided value (v).
*/
func (ds *DataStore) put(k, v string) {
dx := Data{key: k, value: v}
ds.datastore[k] = dx
}
/*
Returns true, if the DataStore has the key (k)
*/
func (ds *DataStore) containsKey(k string) bool {
if _, ok := ds.datastore[k]; ok {
return ok
}
return false
}
/*
Puts the key and value in the DataStore, ONLY if the key (k) is not present.
Returns true, if the put operation is successful,
false if the key (k) ia already present in the DataStore
*/
func (ds *DataStore) putIfAbsent(k, v string) bool {
if val, ok := ds.datastore[k]; ok {
fmt.Println("datastore contains key: ", k, "with value =", val, " --- ", ok)
return false
}
fmt.Println("datastore does not contain ", k)
dx := Data{key: k, value: v}
ds.datastore[k] = dx
return true
}
/*
Returns the Data value associated with the key (k).
*/
func (ds *DataStore) get(k string) Data {
return ds.datastore[k]
}
/*
Removes the entry for the given key(k)
*/
func (ds *DataStore) removeKey(k string) {
delete(ds.datastore, k)
}
/*
Removes the entry for the given key(k)
*/
func (ds *DataStore) removeKeys(k ...string) {
for _, d := range k {
delete(ds.datastore, d)
}
}
/*
Prints the keys and values
*/
func (ds *DataStore) print() {
for k, v := range ds.datastore {
fmt.Println(k, " ", v)
}
}
func main() {
fmt.Println("Hello, playground")
ds := newDataStore()
ds.print()
ds.put("D1", "V1")
ds.put("D2", "V2")
ds.put("D3", "V3")
fmt.Println("datastore with initial values")
ds.print()
ds.put("D1", "UpdatedData for D1")
ds.put("D2", "UpdatedData for D2")
ds.put("D3", "UpdatedData for D3")
fmt.Println("datastore with updated values")
ds.print()
fmt.Println("datastore: putIfAbsent");
ds.putIfAbsent("D3", "Duplicate Key")
ds.putIfAbsent("D4", "V4")
ds.putIfAbsent("D5", "V5")
fmt.Println("datastore with new values")
result := ds.get("D1")
fmt.Println("fetching the value for D1: result: ", result)
testKey := "D4"
//testKeys := [2]string{"D5", "D2"}
fmt.Println("datastore: containsKey: ")
if ok := ds.containsKey(testKey); ok {
fmt.Println("has key ", testKey, ok)
} else {
fmt.Println("has no key ", testKey, ok)
}
ds.print()
ds.removeKey(testKey)
fmt.Println("afer removing ", testKey)
ds.print()
fmt.Println("afer removing ", "D5", "D1")
ds.removeKeys("D5", "D1")
ds.print()
}```
[1]: https://play.golang.org/p/4FEGkImcCKB