Comparing Values in Go

Vladimir Vivien
Dec 18, 2016 · 6 min read

Comparing Values

Boolean

var a := trueif a != (10 == 20) {
fmt.Println("a not true")
}
// following blows up at compilation
if a == 1 { ... }

Integer and Floating-point numbers

import (
"fmt"
"math"
)
func main() {
a := 3.1415
if a != math.Pi {
fmt.Println("a is not pi")
}
}
func main() {
a := 3.1415
b := 6
if a != b {
fmt.Println("a is not b")
}else if a <= b {
fmt.Println("a is in the right position")
}
}
// Boom, blows up with:
// operation: a != b (mismatched types float64 and int)
func main() {
a := 3.1415
b := 6
if a != float64(b) {
fmt.Println("a is not b")
}
}

Complex Numbers

func main() {
a := complex(-3.25, 2)
b := -3.25 + 2i
if a == b {
fmt.Println("a complex as b")
}
}
func main() {
a := complex(-3.25, 2)
b := -3.25 + 2i
if a < b {
fmt.Println("a complex as b")
}
}
//compilation error
//invalid operation: a <= b (operator <= not defined on complex128)

String Values

func main() {
cols := []string{
"xanadu", "red", "fulvous",
"white", "green", "blue",
"orange", "black", "almond"}
for _, col := range cols {
if col >= "red" || col == "black" {
fmt.Println(col)
}
}
}

Struct Values

func main() {
p1 := struct {a string; b int}{"left", 4}
p2 := struct {a string; b int}{a: "left", b: 4}
if p1 == p2 {
fmt.Println("Same position")
}
}
func main() {
p1 := struct {a string; b int}{"left", 4}
p2 := struct {a string; b int32}{a: "left", b: 4}
if p1 > p2 {
fmt.Println("Same position")
}
}
// compilation error
// invalid operation: p1 > p2 (operator > not defined on struct)

Arrays

func main() {
pair1 := [2]int {4, 2}
pair2 := [2]int {2, 4}
if pair1 != pair2 {
fmt.Println("different pair")
}
}

Pointers

func main() {
pair := [2]int {4, 2}
ptr := &[2]int {4, 2}
ptr2 := &pair

if &pair != ptr {
fmt.Println("pointing different")
}
if &pair == ptr2 {
fmt.Println("pointing the same")
}
}

Interfaces

type shape interface {
area() int
}
type rectangle struct {
l int
w int
}
func (r rectangle) area() int {
return r.l * r.w
}
type square struct {
l int
}
func (s square) area() int {
return s.l * s.l
}
func main() {
var r0 shape = rectangle{3, 6}
var r1 shape = rectangle{6, 3}
var r2 shape = rectangle{3, 6}
var s0 shape = square{5}

if r0 == r2 {
fmt.Println("r0 and r2 same shapes")
}

fmt.Println("r1 and s0 equal", (r1 == s0))
}

Channels

func main() {
ch0 := make(chan int)
ch1 := make(chan int)
ch2 := ch1

fmt.Println(“ch0 == ch1”, (ch0==ch1))
fmt.Println(“ch1 == ch2”, (ch1==ch2))
}

Conclusion

Learning the Go Programming Language

Short and insightful posts for newcomers learning the Go programming language

Vladimir Vivien

Written by

Software Eng • Go Programming • Kubernetes • Author http://golang.fyi

Learning the Go Programming Language

Short and insightful posts for newcomers learning the Go programming language