Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

New vs named return as pointer in go

My function is working file with this signature

func GetFileMetadata(f *multipart.FileHeader) *FileMetadata {
    d := new(FileMetadata)

    // ...

    if typ, err := GetFileRealType(f); err == nil {
        d.Type = typ.MIME.Value
        fileExt = "." + typ.Extension
    } else {
        d.Type = "unknown"
    }

    return d
}

With following signature it doesn’t.

func GetFileMetadata(f *multipart.FileHeader) (d *FileMetadata) {

    // ...

    if typ, err := GetFileRealType(f); err == nil {
        d.Type = typ.MIME.Value
        fileExt = "." + typ.Extension
    } else {
        d.Type = "unknown"
    }

    return
}

Getting nil pointer dereference err. What is the reason?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you use a named return variable, that variable is declared within the function body with an initial value set to its zero value. So in your second example where you used a named return with d, d is a nil pointer. You should still initialize it:

    d = new(FileMetadata)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading