-1

Option 1

var employees []Employee
session.Employees = employees

Option 2

session.Employees = []Employee{}

What, if any, is the difference in the two Golang code options, with respect to session.Employees after execution?

icza
  • 389,944
  • 63
  • 907
  • 827
Amitabh
  • 162
  • 9

1 Answers1

4

Your first version assigns the value of the employees variable to session.Employees. It will be the zero value of the type []Employee, which is nil. You could simply write this as:

session.Employees = nil

Your second version assigns the value of a composite literal, which will be an empty (length=0, capacity=0) but non-nil slice.

See related questions:

nil slices vs non-nil slices vs empty slices in Go language

What is the point of having nil slice and empty slice in golang?

Correct way to initialize empty slice

icza
  • 389,944
  • 63
  • 907
  • 827