Does the named return slice need to be made in golang?

Issue

Suppose a function such as:

func returnNamedSlice(num int) (s []int)

I am able to do the following directly in the code, as if s was already made.

s = append(s, 5)

But if I don’t do the above (append operation), then s is always nil and the returned s is also nil.

Why this design? This seems very inconsistent.

Solution

The following statement works because a nil slice is handled the same as an empty slice by the append function.

 s = append(s, 5)

Nil slices are handled the same as empty slices because the length and capacity of a nil slice are defined to be zero, the same as an empty slice.

The feature is unrelated to named return values. Here’s a demonstration without return values:

  var x []int           // x is a nil slice of int
  fmt.Println(x)        // prints []
  fmt.Println(x == nil) // prints true
  x = append(x, 5)      // x is slice with one element, 5
  fmt.Println(x)        // prints [5]
  fmt.Println(x == nil) // prints false

A confusing point when examining these features is that the fmt package prints nil slices and empty slices with the same representation, [].

Answered By – RedBlue

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.