Skip to content

Return Empty Slice in Golang

If you have to return an empty slice (of any type) there are three ways to do it.

  1. Return a direct slice:
func getNames() []string {
	return []string{}
}

2. Return a variable:

func getNames() []string {
	var names []string
	return names
}

3. Return the variable initialized in the function declaration and you don’t have to say what to return:

func getNames() (names []string) {
	return
}

Note: The second and the third solution are the same.

Leave a Reply

Your email address will not be published. Required fields are marked *