Get Started with Go as Python Programmer — Code Examples

Zaid Afzal ⚡️
7 min readJan 5, 2023

--

If you are a Python programmer looking to get started with Go, here are some tips to help you get up to speed quickly.

  1. Go has a very different syntax from Python, so it’s important to familiarize yourself with Go’s syntax.
  • Go uses curly braces to define code blocks, rather than indentation
  • Go has no classes, but it does have structs which can be used to define types
  • Go has a very simple type system and does not have inheritance
  • Go uses the “:=” operator to define variables, rather than “=”

2. Go has a built-in concurrency model which makes it easy to write programs that can execute multiple tasks concurrently. This is a powerful feature of Go that can be difficult to understand at first, but it is worth learning because it can greatly improve the performance of your programs.

Learning Go with Python (17 Aspects)

1. Single package import

Python

import os

Go

import "os"

2. Multiple packages import

Python

import os, sys, json

Go

import (
"os"
"fmt"
"encoding/json"
)

3. Import specific method/class from module — not everything

Python

from json import load, dump

Go

// In Go, you can't import specific function/variable. 
// Everything gets imported by default.

4. Single Line Comment

Python

# this is single line comment

Go

// This is single line comment

5. Multi Line Comment

Python

''' This is 
a multi
line comment.
'''

Go

/* This is 
a multi
line comment
*/

6. Main Function

Python

# Not mandatory to use
if __name__ == "__main__":
# your code here

Go

// mandatory as main function is the entry point.
func main(){
// your code here
}
// it takes no arguments and should not return anything.

7. Conditional Statements: if/else

Python

a = "hello"

if a == "hello":
print("Hello")
elif a == "hi":
print("Hi")
else:
print("Can't understand.")

Go

import "fmt"

var a string = "hello"
if a == "hello"{
fmt.Println("Hello")
}
else if a == "hi"{
fmt.Println("Hi")
}
else{
fmt.Println("Can't understand.")
}

8. Data Type: Integer

Python

# integer
num = 1

Go

// integer
var num int = 1
var num int8 = 1
var num int16 = 1
var num int32 = 1
var num int64 = 1
var num uint8 = 1
var num uint16 = 1
var num uint32 = 1
var num uint64 = 1

9. Installing Single Package

Python

pip install flask

Go

# downloads source code
go get github.com/z4id/awesome-go

# compiles from source code after downloading source as executable
go install github.com/z4id/awesome-go

10. Installing All Packages from Requirements File

Python

pip install -r requirments.txt

Go

go mod tidy
# It uses go.mod and go.sum file in project directory

11. Dictionary — Map Data Type

Basically a key/value pair.

Python

# Python has dictionary data type for storing key, value pairs
animal_count = {"cat": 2, "dog": 5, "cow": 1}

Go

// Go has map data type for storing key, value pairs and its always 
// pointer like reference object.
animal_count := map[string]int{"cat": 2, "dog": 5, "cow": 1}

12. Duck Typing

It refers to a style of typing in which the type of a value is determined by its behavior rather than its explicit type. This means that you can use values of different types interchangeably as long as they have the same behavior.

In short: If it walks like a duck, and it quacks like a duck, then it must be a duck.

Python

class Duck: 
def __init__(self, name):
self.name = name
def quack(self):
print('Quack!')

class Car:
def __init__(self, make):
self.make = make
def quack(self):
print('I can quack, too!')

def quacks(obj):
obj.quack()

donald = Duck('Donald Duck')
car = Car('Tesla')
quacks(donald) # Output: 'Quack!'
quacks(car) # Output: 'I can quack, too!'

Go

Go does not have a built-in mechanism for duck typing, but you can use interface values to achieve a similar effect.

/* Doesn't support Duck typing like Python or anyother dynamically typed 
programming language, but supports interface which can give this
flexibility of calling single function name on many structs.
*/

/* An interface value is a value that can hold any value that implements a
set of methods. You can use interface values to store values of different
types and then call the same method on all of them, regardless of their
actual types.
*/

type Duck interface {
Quack()
}

type YellowDuck struct{}

func (yd YellowDuck) Quack() {
fmt.Println("Quack!")
}

type Car struct{}

func (c Car) Quack() {
fmt.Println("I can quack, too!")
}

func PlayWithDuck(d Duck) {
d.Quack()
}

yellowDuck := YellowDuck{}
car := Car{}

PlayWithDuck(yellowDuck) // Output: "Quack!"
PlayWithDuck(car) // Output: "I can quack, too!"

13. Type Conversion

Type conversion refers to the process of converting a value from one data type to another data type. This can be useful if you have a value in one type, but you need to use it in a context where a different type is expected.

Python

# Method 1
# You can use the built-in functions int(), float(), and str() to convert
# values to integers, floating-point numbers, and strings, respectively.
x = '10'
y = int(x)
print(y) # Output: 10

z = float(x)
print(z) # Output: 10.0

# You can also use the bool() function to convert a value to a Boolean,
# which is either True or False.

a = 'hello'
b = bool(a)
print(b) # Output: True

# ----------------------

# Method 2
# If you want to convert a value to a specific data type,
# you can use the type() function as well and pass in the
# desired type as an argument.

x = 10
y = type(x)('20')
print(y) # Output: 20

Go

// Method 1
/*
you can use the built-in functions int(), float64(), and string() to
convert values to integers, floating-point numbers, and strings, respectively.
*/
x := "10"
y, _ := strconv.Atoi(x)
fmt.Println(y) // Output: 10

x := "10.5"
y, _ := strconv.ParseFloat(x, 64)
fmt.Println(y) // Output: 10.5

x := 10
y := strconv.Itoa(x)
fmt.Println(y) // Output: "10"

/*
You can also use the bool() function to convert a value to a Boolean,
which is either true or false.
*/
x := "hello"
y, _ := strconv.ParseBool(x)
fmt.Println(y) // Output: true

// -----------------------


// Method 2
/* If you want to convert a value to a specific data type, you can use
the reflect.TypeOf() function to get the type of a value and then use
a type assertion to convert it to the desired type.
*/
x := 10
y := reflect.TypeOf(x)
fmt.Println(y) // Output: int

z := y.(int)
fmt.Println(z) // Output: 10

14. Type Assertion

A type assertion is a statement that allows you to check the type of a variable at runtime.

Python

a = 10
is_int = isinstance(a, int)
print(is_int) # Output: True

assert isinstance(a, int), 'a must be an integer'
# it will throw AssertionError if value of isn't of integer type.

Go

x := "10"
y, ok := x.(int)
fmt.Print(y) // Output: 10

/* It checks if the value stored in the interface variable x is an integer.
If it is, the value is extracted and stored in the variable y. If it is not,
the variable ok is set to false and the value of y is the zero value of
the type int.
*/

15. Closure

A closure is a function that retains the bindings of the free variables that exist when the function is defined, so that they can be used later when the function is invoked.

To create a closure, you define a nested function and then reference a variable from the enclosing scope in the body of the function. The inner function is then returned to the caller, along with the current bindings of the free variables.

Python

def outer(n):
def multiply(x):
print(x * n)
return multiply

closure = outer(2)
closure = outer(3)

closure(4) # Output: 8
closure(4) # Output: 12

Go

func outer(n int) func() {
func multiply(x int) {
fmt.Println(x * n)
}
return multiply
}

closure := outer(2)
closure(4) // Output: 8

closure := outer(3)
closure(4) // Output: 12

16. Anonymous/Inline Function

Python

''' 
It is defined without a name. These types of functions are often
referred to as "lambda functions," because they are defined using
the lambda keyword.

Lambda functions are useful when you need to create a small, one-time use
function in a context where a full function definition is not necessary
or appropriate. They are often used as arguments to other functions,
or as part of functional programming constructs such as map(), filter(),
and reduce().

The function body must be a single expression, and the result of the
expression is the return value of the function.
'''

square = lambda x: x**2
print(square(5)) # Output: 25

numbers = [1, 2, 3, 4, 5]
squares = map(lambda x: x**2, numbers)
print(list(squares)) # Output: [1, 4, 9, 16, 25]

add = lambda x, y: x + y
print(add(3, 4)) # Output: 7

Go

/*
Often referred to as "anonymous functions" or "function literals."

often used as arguments to other functions, or as part of functional
programming constructs such as map(), filter(), and reduce().

Has the same structure as a regular function, but it is not bound to an
identifier
*/

square := func(x int) int {
return x * x
}
fmt.Println(square(5)) // Output: 25

numbers := []int{1, 2, 3, 4, 5}
squares := map(func(x int) int { return x * x }, numbers)
fmt.Println(squares) // Output: [1 4 9 16 25]

add := func(x, y int) int {
return x + y
}
fmt.Println(add(3, 4)) // Output: 7

17. Exception Handling

I hope this helps! Let me know if you have any questions.

--

--