Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang

What are optional data types in Golang?

Abdul Monum

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 a bool or a nil.
  • String: either a string or a nil.
  • Int: either an int or a nil.
  • Duration: either a time.Duration or a nil.
  • Uint: either a uint or a nil.
  • Float64: either a float64 or a nil.

Example

package main
import "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”.

RELATED TAGS

golang

CONTRIBUTOR

Abdul Monum
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring