"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Correctly Implement Valuer and Scanner for Custom Types in Go?

How to Correctly Implement Valuer and Scanner for Custom Types in Go?

Published on 2024-11-18
Browse:315

How to Correctly Implement Valuer and Scanner for Custom Types in Go?

Golang Type Assertion: Implementing Valuer and Scanner for Custom Types

When working with custom types in Go, such as those based on strings, it can be necessary to implement the Valuer and Scanner interfaces for interacting with database drivers. This enables the serialization and deserialization of your custom types to and from database values.

In the provided code, an attempt was made to implement a Role type and its associated Valuer and Scanner methods. However, an error was encountered:

cannot convert value.(string) (type string) to type *Role

To correct this error, the Scan method can be modified as follows:

func (r *Role) Scan(value interface{}) error {
    *r = Role(value.(string))
    return nil
}

This modification ensures that the value retrieved from the database is properly assigned to the Role pointer. Additionally, the Value method should have the following signature:

func (r Role) Value() (driver.Value, error) {
    return string(r), nil
}

Note that this implementation does not handle or produce NULL values.

By following these suggestions, you can successfully implement the Valuer and Scanner interfaces for your custom types and enable seamless interaction with database drivers.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3