TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang nil (Cannot Use nil as Type)

Use the nil keyword to test uninitialized slices. A string cannot be nil.
Nil. In Go we use the constant nil instead of null. This means "nothing exists." A slice can be uninitialized, and in this state it is nil. We must be careful with nil things.Built-Ins
Unlike in many languages, we cannot use nil in place of a string. Nil is not allowed in string typed collections. An empty string may be used instead.
An example program. Let us consider this example Go program. When we use the "var" keyword, we declare variables. But these variables are not initialized when created.

And: A slice (or interface) is at first uninitialized. It is nil. We can test for uninitialized things with nil.

SliceInterfaceIf
Golang program that uses uninitialized slice package main import "fmt" func main() { // This is an uninitialized slice. var temp []int // The uninitialized slice is nil. if temp == nil { fmt.Println("Uninitialized slice is nil") } } Output Uninitialized slice is nil
String error. This program shows the error when trying to use nil in a string slice. Here we could use an empty string to mean "no value."

Important: We cannot use nil in a slice or array of strings. The nil constant has no type—so it cannot substitute for a string.

Golang program that causes nil, string error package main func main() { temp := []string{} temp = append(temp, nil) } Output # command-line-arguments C:\programs\file.go:8: cannot use nil as type string in append
Some research. It is useful to research each programming concept until you understand it. In Go we find that slices can be left uninitialized, and these equal nil.

Quote: The value of an uninitialized slice is nil (Go Programming Language).

A review. With nil we can test for uninitialized (or nonexistent) things. A slice variable that has not been assigned yet is nil.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf