Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is (nil) doing in this context []string(nil)

Tags:

go

I was looking at the Slice Tricks: https://github.com/golang/go/wiki/SliceTricks

and I noticed in their copy example they have []T(nil)

I haven't seen (nil) like this before and I can't find any documentation on using it or what exactly it accomplishes (I know it's self explanatory but I want to know how it acts the same as make or []string{}

the only reference I can find by googling "golang (nil) slice" is

Since the zero value of a slice (nil) acts like a zero-length slice, you can declare a slice variable and then append to it in a loop:

But it doesn't say where it can be used or exactly what it accomplishes, like can I use this with structs or whatever I want?

e.g.:

package main

import "log"

func main() {
    str := []string{"Hello", "Bye", "Good Day", "????????"}
    cop := append([]string(nil), str...)    

    log.Println(str)
    log.Println(cop)
}

I'm strictly only curious about how (nil) operates, and what it can operate on.

Like does

[]string(nil)

Operate the same as

[]string{}

or what is the difference here

like image 624
Datsik Avatar asked Jan 09 '16 00:01

Datsik


People also ask

Can a string be nil?

A string cannot be nil, because the data structure in go doesn't allow it. You can have a pointer to a byte array holding character representations in go be null, but that isn't a string.

Is empty slice nil?

An empty slice is a slice that is declared by using the built-in make function and it doesn't have nil as its zero value.

What is nil Golang?

About nil. nil is a predefined identifier in Go that represents zero values of many types. nil is usually mistaken as null (or NULL) in other languages, but they are different. Note: nil can be used without declaring it.

Is nil or empty Golang?

Nil represents a zero value in Golang. As you may already know, zero values are the "default" value for defined variables in Go. This means that some types doesn't cannot hold empty values, instead acquiring zero values upon initialization to get rid of the problem of checking values for emptyness.


1 Answers

This is a type conversion, converting a nil to a slice.

These are equivalent

var t []string
t := []string(nil)

In both cases, t is of type []string, and t == nil

like image 104
JimB Avatar answered Sep 30 '22 11:09

JimB