How to make a nullable field in a struct

For empty field you can check for empty values which is zero value which is not nil in case of struct.

When storage is allocated for a variable, either through a declaration
or a call of new, or when a new value is created, either through a
composite literal or a call of make, and no explicit initialization is
provided, the variable or value is given a default value. Each element
of such a variable or value is set to the zero value for its type:
false for booleans, 0 for numeric types, “” for strings, and nil for
pointers, functions, interfaces, slices, channels, and maps.

In your case are using the Struct not a pointer to struct. The value is not nil it is empty though

var user User
fmt.Println(user == User{}) // will print true

But since in your case the returned value is pointer to struct *User, error you can check for nil

var user *User
fmt.Println(user == nil) // will print true

Create struct field that is a pointer.

testCases := []struct {
    name          string
    testUserID    uint
    expected      *User // <- maybe nil
    expectedError error
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)