cmp.Or()
This is a small demonstration of the cmp.Or()
function provided by the Go standard library.
cmp.Or()
returns the first of its arguments that is not equal to the zero value. If no argument is non-zero, it returns the zero value.
package main
import (
"cmp"
"fmt"
"os"
)
func main() {
ip := os.Getenv("IP")
if ip == "" {
ip = os.Getenv("IP_ADDRESS")
}
if ip == "" {
ip = "127.0.0.1"
}
fmt.Println("IP:", ip)
// This is equivalent to all previous statements
myIP := cmp.Or(os.Getenv("IP"), os.Getenv("IP_ADDRESS"), "127.0.0.1")
fmt.Println("myIP:", myIP)
}
Executing it generates the following output:
$ go run /tmp/or.go
IP: 127.0.0.1
myIP: 127.0.0.1
You can get Mastering Go, 4th edition on Packt, Amazon.com, all other Amazon web sites as well as on other book stores.