4

The docs of gorm https://gorm.io/docs/models.html present an example below.
The field Name and Email are described with string and *string. What is the main difference here?
Also how to provide the datatype for the images field storing a list of images link?
Should it be []string or []*string?

type User struct {
  ID           uint
  Name         string
  Email        *string
  Images       []string
  Age          uint8
  Birthday     *time.Time
  MemberNumber sql.NullString
  ActivatedAt  sql.NullTime
  CreatedAt    time.Time
  UpdatedAt    time.Time
}

2 Answers 2

10

Go has default values for every primitive data types.

int -> 0, string -> "", bool -> false likewise. So if you need to add null value, or load null value to a variable, it should be a pointer. Otherwise it is defaulted.

Default value of a pointer is nil in Go.

And complex data types such as slices, maps keep references. So their default value is nil. So, Images []string here images can be nil.

Below code with pointer types User1 and without pointer types User2 show the difference in default values.

package main

import (
    "fmt"
    "time"
)

type User1 struct {
    Email        *string
    Images       []string
    Birthday     *time.Time
}

type User2 struct {
    Email        string
    Images       []string
    Birthday     time.Time
}

func main() {
    user1 := User1{}
    user2 := User2{}

    fmt.Printf("user1 := %+v \n", user1)
    //Output : user1 := {Email:<nil> Images:[] Birthday:<nil>}
    fmt.Printf("user2 := %+v \n", user2)
    //Output : user2 := {Email: Images:[] Birthday:0001-01-01 00:00:00 +0000 UTC}
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Nipuna. Appreciate the detailed answer.
5

The main difference is that if you use pointers, you can put a null value into the DB, else you must put a string. Esentially if the database field is nullable, you should use pointers.

Comments

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.