edgedb-go
edgedb-go copied to clipboard
Add a Value() function to optional types
The Value() is like the Get() function except that it returns the zero value when the option is not set. This can make the optimal type easier to use in some scenarios.
Thanks for the PR!
This can make the optimal type easier to use in some scenarios.
Can you elaborate on this?
We chose the Get() API instead of using pointers because we wanted maximal type safety. Adding this Value() method seems to largely circumvent the type safety provided by Get().
This is just idiomatic go. Go does not have optional types. In essence, I would not recommend fighting against the language conventions to try to add more safety.
consider this use-case: I'm writing a http handler to expose some data form EdgeDB as an API for my front end and I need to covert the edgeDB result struct to struct that will be sent as a JSON result. Using the value function this is really easy:
// in gin request hander, we do a call to edgeDB to lookup a user by id:
record, _ := dbGet(c, client, id)
type User struct {
Id edgedb.UUID `json:"id"`
FullName string `json:"full_name"`
Picture string `json:"picture,omitempty"` // zero values are special!
}
c.JSON(http.StatusOK, User{
Id: record.id,
FullName: record.fullName,
Picture: record.picture.Value(), // I just want the zero value when not set.
})
Without the Value() function, the caller has to deal with more toil:
picture, _ := record.picture.Value()
c.JSON(http.StatusOK, User{
Id: record.id,
FullName: record.fullName,
Picture: picture,
})
It's quite common across the go ecosystem to use the zero values to mean something like the value not being set.
I understand where you are coming from. While it is common for the zero value to mean unset it is not a rule. I don't think we are ready to commit to this kind of change quite yet. It is easy enough to write a convenience function for this.
type Getter[T any] interface {
Get() (T, bool)
}
func Value[T any](thing Getter[T]) T {
v, _ := thing.Get()
return v
}
What's the downside to adding the Value() function? It seems like having the method can make life easier for many of your users without much harm to anyone else. You guys do want to attract go developers to use your project right?