CSE224 - Go OOP
Class
Named Type
I can create a new named type MyInt that is based on int, but is treated as a distinct type by the compiler.
1 |
|
struct + methods
Go doesn’t have traditional classes, instead, it uses Custom types + attached methods. As a result, structs in go can hold both data and associated methods. Example:
1 |
|
Another example: User behaves just like a class
1 |
|
Constructors
Go does not have built-in constructors. We define a function by ourself as a constructor:
1 |
|
Encapsulation
Go doesn’t use public or private keywords like Java or C++. Instead, it uses capitalization to control visibility.
1 |
|
Composition
Composition over Inheritance: Go doesn’t have classes or inheritance, but it has composition using embedding.
1 |
|
By composition, I can resue methods.
Override
1 |
|
Interface (Polymorphism and Abstraction)
An interface in Go is a set of method signatures. If a type has those methods, it automatically implements the interface.
1 |
|
If the method is defined on a pointer receiver, only the pointer type implements the interface.
1 |
|
In this example, Person
doesn’t implement the interface, but *Person
does, so assigning a Person
to a Greeter
causes an error. (g = &p
works)