Go: Data Types - Booleans and Bytes

1 minute read


:information_source: Note: Read the offical references to get the most updated information.

Type Conversion

Go requires explicit conversion between different types. Converting between types, type casting, is done via a function with the name of the type to convert to (T(v) converts the value v to the type T).

var x int = 42 // x has type int
f := float64(x) // f has type float64 (ie. 42.0)

Arithmetic

Go supports the standard set of arithmetic operators:

+    sum                    // integers, floats, complex values, strings
-    difference             // integers, floats, complex values
*    product                // integers, floats, complex values
/    quotient               // integers, floats, complex values
%    remainder              // integers

&    bitwise AND            // integers
|    bitwise OR             // integers
^    bitwise XOR            // integers
&^   bit clear (AND NOT)    // integers

<<   left shift             // integer << integer >= 0
>>   right shift            // integer >> integer >= 0

The math package contains many helpful mathematical functions.

Arithmetic operations on different types

In many languages you can perform arithmetic operations on different types of variables, but in Go this gives an error:

var x int = 42

// this line produces an error
value := float32(2.0) * x // invalid operation: mismatched types float32 and int

// you must convert int type to float32 before performing arithmetic operation
value := float32(2.0) * float32(x)

Shorthand Assignments

These can be used in shorthand assignments to update and assign a variable using the operator:

a := 1
a += 2 // same as a = a + 2 == 3

Increment and Decrement

There are also two special statements: increment (++) and decrement (–) the value by 1.

a := 10
a++ // same as a += 1

logical operators

Go supports three logical operators that can evaluate expressions down to Boolean values, returning either true or false.

true || false // Output: true
true && false // Output: false
!true // Output: false
The three boolean operators each have a different operator precedence. As a consequence, they are evaluated in this order: ! first, && second, and finally   . If you want to force a different ordering, you can enclose a boolean expression in parentheses (ie. ()), as the parentheses have an even higher operator precedence.
!true && false   // Output: false
!(true && false) // Output: true

Updated:

Leave a Comment