DEV Community

Cover image for Golang for Experienced Developers - Part II
Samarth Gupta
Samarth Gupta

Posted on • Updated on

Golang for Experienced Developers - Part II

Welcome,

This is the second part of Golang tutorial series, if you haven't checked out the first part, do check it out here.

Let's continue where we left off...

Primitive Data Types in Go

Syntax:
var variableName type = value
Enter fullscreen mode Exit fullscreen mode

Following are the types of Primitive Data Types in Go:

Boolean

  • A bool type represents the set of Boolean truth values denoted by the predeclared constants true or false.
  • Supported operators are &&, || and !
  • Use %t to print booleans.
Example:
var flag bool = !(10 > 0 && 20 < 40)
fmt.Printf("%t\n", flag)  // false
Enter fullscreen mode Exit fullscreen mode

Numeric

  • A numeric type represents sets of integer or floating-point values.
  • Architecture dependent types determine their size based on the architecture. Architecture independent types have fixed size.
  • There is no float type, only float32 or float64
  • Precision of float32 is 7 decimal places.
  • Precision of float64 is 15 decimal places.
  • There is no implicit type conversion between any data types. i.e. int16 can't be assigned to int32, to overcome this one must do explicit type conversion.
Architecture Dependent Types:
uint     either 32 or 64 bits
int      same size as uint
uintptr  an unsigned integer large enough to store the uninterpreted bits of a pointer value
Enter fullscreen mode Exit fullscreen mode
Architecture Independent Types:
uint8       the set of all unsigned  8-bit integers (0 to 255)
uint16      the set of all unsigned 16-bit integers (0 to 65535)
uint32      the set of all unsigned 32-bit integers (0 to 4294967295)
uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)

int8        the set of all signed  8-bit integers (-128 to 127)
int16       the set of all signed 16-bit integers (-32768 to 32767)
int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64       the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

float32     the set of all IEEE-754 32-bit floating-point numbers
float64     the set of all IEEE-754 64-bit floating-point numbers
Enter fullscreen mode Exit fullscreen mode
Explicit Type Conversion:
var val1 int16 = 32
var val2 int32 = int32(val1)   // explicit conversion
Enter fullscreen mode Exit fullscreen mode

Complex Number

  • Go provides a two new data type to store complex numbers which are architecture independent.
  • Complex arithmetic is supported.
  • Use complex(real, imaginary) function to create complex numbers & real() & imag() function to extract real & imaginary part.
  • Use %v to print complex numbers.
complex64   the set of all complex numbers with float32 real and imaginary parts
complex128  the set of all complex numbers with float64 real and imaginary parts
Enter fullscreen mode Exit fullscreen mode
Example:
var cp1 = complex(1.2, 2.1)
var cp2 = complex(3.4, 5.8)
fmt.Println(real(cp1), imag(cp2))  // 1.2  5.8
fmt.Printf("%v\n", cp1 + cp2)     // (4.6 + 7.9i)
Enter fullscreen mode Exit fullscreen mode

Character

  • It's a special case of integer type.
  • Use \u(4 hex digit) or \U(8 hex digits) for unicode
  • User %c or %U for printing.
byte        alias for uint8, for storing ASCII characters
rune        alias for int32, for storing UTF-8 characters
Enter fullscreen mode Exit fullscreen mode
Example:
var char1 byte = 65           // ASCII 'A'
var char2 byte = '\x41'       // ASCII 'A'
var char3 rune = '\u0041'     // Unicode 'A'
var char4 rune = '\U00101234' // Unicode
fmt.Printf("%c %U\n", char1, char4)   // A U+1012334
Enter fullscreen mode Exit fullscreen mode

Pointer

  • Pointers are variables that store memory address.
  • This is exactly similar to C++ except pointer arithmetic isn't supported in Go.
  • Pointer variables are stored in heap and are garbage collected.
  • AddressOf(&) and dereference(*) operators act same as C++.
  • Use %p to print pointers.
Syntax:
var identifier *type = address
Enter fullscreen mode Exit fullscreen mode
Example:
var num int = 6
var ptr *int = &num
fmt.Printf("%p\n", ptr)    // address of num

*ptr = 20                  // changes num to 20
fmt.Println(num)           // 20

ptr++                      // illegal, pointer arithmetic not supported
const val = 10
ptr = &val                 // illegal, why?
Enter fullscreen mode Exit fullscreen mode

See this for why.

String

  • string are immutable in Go for the same reason why it's immutable in Java.
  • Strings are not null terminated like C/C++.
  • Indexing & slicing is allowed.
  • Use len(str) for string length.
  • Can't take address of string character (&str[i] illegal)
  • Comparison operators compare bytes.
  • Strings are initialised with double quotes or back-ticks.
  • Defaults to empty string ("")
Example:
var str string = "Let's Go"
fmt.Println(len(str))       // 8
var str2 string = "C:\newfolder\text.txt"
fmt.Println(str2)     // C:
                      // ewfolder    ext.txt, bcoz escape sequence

var str3 string = `C:\newfolder\text.txt`   // raw string
fmt.Pritln(str3)     // C:\newfolder\text.txt

Enter fullscreen mode Exit fullscreen mode
Concatenation & Update:
var a = "Hello "
var b = "world"
var c = a + b      // Hello world, concatenation
a += b          // Hello world, update but create new object bcoz immutability
Enter fullscreen mode Exit fullscreen mode
Indexing:
var str = "hello"
fmt.Printf("%c\n", str[0]) // h
str[0] = 'j'             // illegal
Enter fullscreen mode Exit fullscreen mode
Slicing:
var str = "hello"
fmt.Println(str[1:4])   // ell, index 1-3
fmt.Println(str[:4])    // hell, index 0-3
fmt.Println(str[1:])    // ello, index 1-end
fmt.Println(str[:])     // hello, index 0-end

fmt.Println(str[-1])    // illegal, but legal in Python
fmt.Println(str[:-1])   // illegal, but legal in Python
Enter fullscreen mode Exit fullscreen mode

String Conversions & Functions

  • There are two packages available for string conversions and string functions in Go.

For string conversion:

import "strconv"

Example:
package "main"
import "strconv"
import "fmt"

func main() {
    // string to numeric
    num, _ := strconv.Atoi("1234")
    fmt.Println(num)    // 1234 - int
    fval, _ := strconv.ParseFloat("3.46", 64)  // (str, floatSize)
    fmt.Println(fval)   // 3.46 - float64
    num2, _ := strconv.ParseInt("123", 10, 64) // (str, base, intSize)
    fmt.Println(num2)   // 123 - int64

    // numeric to string
    str1 := strconv.Itoa(789)
    fmt.Println(str1)    // 789 - string
    str2 := strconv.FormatFloat(3.45, 'f', -1, 32)
    fmt.Println(str2)    // 3.45 - string
    str3 := strconv.FormatInt(1234, 10)
    fmt.Println(str3)    // 1234 - string
}
Enter fullscreen mode Exit fullscreen mode

For string functions:

import "strings"

Useful Functions:
func Contains(s, substr string) bool
func Count(s, sep string) int
func HasPrefix(s, prefix string) bool
func HasSuffix(s, suffix string) bool
func Index(s, sep string) int
func Join(a []string, sep string) string
func LastIndex(s, sep string) int
func Repeat(s string, count int) string
func Replace(s, old, new string, n int) string
func Split(s, sep string) []string
func ToLower(s string) string
func ToUpper(s string) string
func Trim(s string, cutset string) string
Enter fullscreen mode Exit fullscreen mode

With this, concludes the second part of this tutorial. Next up we have control constructs in Golang. Coming soon...

Discussion (2)

Collapse
maxatome profile image
Info Comment hidden by post author - thread only accessible via permalink
Maxime Soulé
var flag bool = ^(10 > 0 && 20 < 40)
Enter fullscreen mode Exit fullscreen mode

^ is not a boolean operator, you probably mean ! instead.

Collapse
livesamarthgupta profile image
Samarth Gupta Author

Thanks for correcting me there.

Some comments have been hidden by the post's author - find out more