[Golang] Synonyms with Python Class


Simple example of writing Python class synonyms in Golang.

Python vs Golang
Python Go

Run Code on repl.it

class Square:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def Area(self):
        return self.x * self.y

if __name__ == "__main__":
    sq = Square(2, 3)
    print(sq.Area())

Run Code on Go Playground

package main

import "fmt"

type Square struct {
        x int
        y int
}

func (s *Square) Area() int {
        return s.x * s.y
}

func main() {
        // no constructor in Golang
        sq := Square{2, 3}

        // calculate area
        fmt.Println(sq.Area())
}

References:

[1]golang class inheritance
[2]Golang concepts from an OOP point of view - GitHub
[3]Go Object Oriented Design (reddit)