Return nil for a struct in Go

You’re assigning your item variable wrong. You said you tried item := *Item{}, whereas the way to create a pointer is either through the use of the new builtin, or to create a literal, and the address-of operator (&). The latter is the approach you’ll most commonly see in golang. There are some cases where one would use new, but in this case, I’d go for the second approach:

So either:

item := &Item{}
// or
item := new(Item)

Lastly, you can keep the code as-is, and just return a pointer at the end:

item := Item{}
// some code here
return &item, nil

In case where you have to return an error, you can still have return nil, err

So putting everything together:

// return *Item instead of Item
func Handler(request Request) (*Item, error) {
   // your code here, eg:
   item := Item{}
   if err := dynamodbattribute.UnmarshalMap(result.Item, &item); err != nil {
        return nil, err
    }
    return &item, nil
}

Alternatively, assign item as a pointer from the start

func Handler(request Request) (*Item, error) {
   // your code here, eg:
   item := &Item{}
   if err := dynamodbattribute.UnmarshalMap(result.Item, item); err != nil {
        return nil, err
    }
    return item, nil
}

Leave a Comment

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