Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in string and *string in Gorm model declaration

Tags:

go

go-gorm

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
}
like image 547
Rajan Chauhan Avatar asked Oct 21 '25 04:10

Rajan Chauhan


2 Answers

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}
}
like image 162
nipuna Avatar answered Oct 22 '25 16:10

nipuna


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.

like image 38
aaronlukacs Avatar answered Oct 22 '25 16:10

aaronlukacs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!