-
Notifications
You must be signed in to change notification settings - Fork 65
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Go-datastore and return values #28
Comments
package encodingds
import (
"encoding/json"
ds "github.com/jbenet/go-datastore"
)
func Wrap(child ds.Datastore) *Datastore {
return &Datastore{child}
}
type Datastore struct {
D ds.Datastore
}
func (d *ds.Datastore) Get(k ds.Key) (interface{}, error) {
data, err := d.D.Get(k)
if err != nil {
return nil, err
}
var v2 interface{}
err = json.Unmarshal(data, &v)
return v2, err
}
func (d *ds.Datastore) Put(k ds.Key, v interface{}) error {
data, err := json.Marshal(data, &v)
if err != nil {
return err
}
return d.Child.Put(k, data)
}
func (d *ds.Datastore) Delete(k ds.Key) error {
return d.D.Delete(k)
}
func (d *ds.Datastore) Has(k ds.Key) (bool, error) {
return d.D.Has(k)
}
func (d *ds.Datastore) Query(k ds.Query) {
// ok, this one is harder...
} |
FWIW, I think a more elegant API would be one where Get returns its result in one of its arguments, i.e.
Now the datastore implementation doesn't need to allocate its return value, so there isn't any need for type bookkeeping either. If necessary, you could still let the datastore implementation decide the return type by passing an empty interface pointer to v. I don't think this would make wrapper datastores any harder to implement either (though having to declare a return variable before every call to Get can get a bit messy.) |
hmmm yeah worth considering. |
Old thread, but happy so show support for the out param ida. It would bring the store interface in line with the (now standard lib) RPC package, which might open the door to some of the other interesting stuff RPC does w Register, protobuf under the hood, etc. |
@b5 Yeah, we've been thinking about reworking the interfaces here soon. If you're interested in pushing that forward, you could open a new issue and propose interface changes. |
Datastore.Get returns its result as a return value, which means that the Datastore implementation needs to allocate it. But if one wishes to store arbitrary types of data into a datastore, how can Get know what type of value to allocate? The only ways I can think of are
but these would bring considerable complexity to any Datastore implementation that wishes to allow storage and retrieval of arbitrarily typed data. Am I missing something obvious, or is this by design? Should any unmarshaling from datastore representations to Go objects (and vice versa) be the client code's responsibility?
The text was updated successfully, but these errors were encountered: