Custom golang sql.NullString Stringer Interface

Viewed 438

I want to override the Stringer interface for all instances sql.NullString so that the output of an instance is instance.String rather than { instance.String, instance.Valid }.

The normal way of doing this is to provide a Stringer interface. With sql.NullString a Stringer interface method fails to compile as there is already a String field.

The workaround is to just use instance.String everywhere.

type NullString sql.NullString

// this fails to compile as sql.NullString has a field named String  
func (x *NullString) String() string {
    if !x.Valid {
        x.String = ""
    }
    return x.String
}

How can a Stinger interface be created if a struct already, like sql.NullString, has a String field?

2 Answers

I would recommend extending the sql.NullString and overriding or adding methods to the extended type.

// NS extends sql null string
type NS struct{ sql.NullString }

func (s NS) String() string {
    return s.NullString.String
}

NS will have the methods of sql.NullString aswell as the methods that are aded to NS itself as well.

Here is a sample usage in playgorund


import "database/sql/driver"

type NullString struct { ns sql.NullString }

func (s *NullString) Scan(value interface{}) error {
    return s.ns.Scan(value)
}

func (s NullString) Value() (driver.Value, error) {
    return s.ns.Value()
}

func (s NullString) String() string {
    return s.ns.String
}
Related