2

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?

3
  • 2
    Note: type NullString sql.NullString "loses" the Scan and Value methods, therefore an instance of your NullString will lose its purpose. Commented Jan 4, 2021 at 7:36
  • 1
    "I want to override the Stringer interface for all instances sql.NullString" makes no sense as you cannot do this in Go. You cannot override. Let go of OOP terms which make no sense in Go. Commented Jan 4, 2021 at 7:52
  • @Volker Happy to reword the question. Commented Jan 4, 2021 at 21:01

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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
}

4 Comments

The answer is correct - but extending sql.Nullstring avoids the need to redefine all existing and future (and non-overwritten) methods.
@chris_f How would you extend sql.NullString ?
@KeithJohnHutchison Go does not support type extensions, so my guess is that chris_f is referring to embedding the type just like it's demonstrated in Sarath's answer.
As @mkopriva points out: you cannot extend an existing type or overwrite its methods such that the change shows up everywhere in a transparent manner. Providing a new type that embeds the sql.NullString anonymously is the only relief that I'm aware of. There you can add and/or overwrite methods as necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.