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
proposal: database/sql: add a common method to unwrap value of sql.Null* types #63633
Comments
ISTM, it should be called "wrap" not "unwrap" because you are wrapping it in the any type interface. Also, I think you should return a zero T, not nil interface in the invalid case, so callers can still use a type switch to figure out what type it was supposed to be. // Wrap the value of n in an interface for use in dynamic type switches.
// Even if n is invalid, it will still return a value that is of concrete type T.
func (n Null[T]) Wrap() (value any, valid bool) {
if !n.Valid {
var zero T
return zero, false
}
return n.V, true
} |
I agree. In that case wouldn't it more appropriate to for the return type to be |
I thought that at first too, but no because you want to be able to do type NullWrap interface {
Wrap() (value any, valid bool)
}
if nw, ok := val.(NullWrap); ok {
rval, ok := nw.Wrap()
switch rval.(type) {
// etc.
}
} If the interface were generic, you couldn't do a runtime assert of I don't think NullWrap needs to be defined in the sql package though. Let callers who need it define it on their end. |
If the interface is not declared, it will not be documented. Having documentation for it is part of the proposal. |
I called it I think that the |
To help understand the motivation behind the proposal, could you give some practical examples of a use-case or a problem, where one wanted to unpack some The current version mentions:
Note that a user could always define their own nullable types, e.g. |
Proposal
Add an interface to
database/sql
implemented bysql.Null*
types to unwrap the NULL or the value:(names to be debatted)
Extend
sql.Null*
types to implement it:Why?
There is currently no builtin generic way to unwrap the value of types
sql.Null
* (sql.NullBool
,sql.NullByte
,sql.NullInt16
,sql.NullInt32
sql.NullInt64
,sql.NullFloat64
,sql.NullString
,sql.NullTime
).But at least the list of types was known, so it was possible to use a type switch.
With the addition of
sql.Null[T]
(#60370) for Go 1.22 the type switch solution will not be enough.The only ways to unwrap an
sql.Null[T]
are just hacks using either thedriver.Valuer
interface orreflect
:(full example: https://go.dev/play/p/DnStyHLekX1?v=gotip)
A common method available on
sql.Null*
types would allow to have an efficient unwrapping and be type safe as unwrapping could be done after an interface check.That interface could also help to distinguish types that are able to represent a
NULL
value (types that never returnvalid == false
should not implement it).The text was updated successfully, but these errors were encountered: