What are optional data types in Golang?
Types | Examples |
elementary (or primitive) | int, float, bool, string |
structured (or composite) | structs, map, slice, array, channel |
interfaces | describe the behavior of a type |
Variables contain data, and data can be of different data types, or types for short. Golang is a statically typed language; this means the compiler must know the types of all the variables, either because they are explicitly indicated or because the compiler can infer the type from the code context. A type defines the set of values and the set of operations that can take place on those values.
Optional data types in Golang are version primitive types that can be nil. For example, an optional string would mean a string and a value indicating not a string, which is nil. The package optional provides the access to optional types in Golang. Below are the optional types in Golang:
Bool: either aboolor anil.String: either astringor anil.Int: either anintor anil.Duration: either atime.Durationor anil.Uint: either auintor anil.Float64: either afloat64or anil.
Example
package mainimport "fmt"import "optional"func main() {var myString optional.String;fmt.Printf(myString);myString = "Hello World"fmt.Printf(myString);}
Output
< nil >
Hello World
Explanation
First, we import the package optional to use the optional data types. Then, we declare myString variable, which is of the type String. Since no value is assigned to myString when it is declared, the first print statement prints nil to represent the lack of value. Then, the string “Hello World” is assigned to myString, and it prints the string “Hello World”.
Free Resources