DEV Community

loading...

Discussion on: How to let OOP world and dive in golang mindset?

Collapse
nektro profile image
Meghan (she/her) • Edited

Many OOP languages have a concept of classes. Go and other compiled-to-assembly languages have not done this to this day but Go is actually the closes OOP language that I've seen that is natively compiled.

As you've already seen, Go instead has structs. These are a special data type so that the compiler can right the assembly to be as memory efficient as possible since with structs, the compiler is going to be able to figure out exactly how many bytes an object will occupy.

On to functions. As you probably already know when you call a function the parameters to that function can either be passed-by-value or passed-by-reference. In native languages, pass-by-reference are called pointers. Pointers are a new data type type that most higher level languages are able to abstract away from but require a basic understanding to understand why Go, Rust, and C functions are defined the way they are. In a high level language, you can make a class with object methods that can use this. In Go, all functions are defined in the top level and "this" has to be defined as a pointer parameter. Kinda anyways. Let's see.

class Rectangle {
    function __construct(x, y, width, height) {
        this.x = x;
        this.y = y;
        this.w = width;
        this.h = height;
    }
    function area() {
        return this.w * this.h;
    }
}

$rect = new Rectangle(0, 0, 6, 4);
echo $rect.area() . "\n"; // 24

vs.

type Rectangle struct {
    width int
    height int
}

func (r *Rectangle) area() int {
    return r.width * r.height
}

func main() {
    rect := Rectangle{width: 6, height: 4}
    fmt.Println("area: ", rect.area()) // 24
}

See gobyexample.com/ for more!

Collapse
gsvaldevieso profile image
Guilherme Soares Valdevieso Author

Hi, Sean.

Thanks for your response.

You has tell me about the structure and how golang works when compared to OOP languages. But my main doubt is about the good practices when we are building applications, as the links that I put ahead.

Thank you again!

Collapse
nektro profile image
Meghan (she/her)

Hi, for SOLID, Go interfaces are actually really cool and I think this site would help a lot: gobyexample.com/interfaces

I also think this would be a good read, if you haven't read it already :D