Golang methods: Difference between revisions
From wikinotes
No edit summary |
|||
(2 intermediate revisions by the same user not shown) | |||
Line 5: | Line 5: | ||
= Adding Methods = | = Adding Methods = | ||
<blockquote> | <blockquote> | ||
Basics | |||
<syntaxhighlight lang="go"> | <syntaxhighlight lang="go"> | ||
type Rectangle struct { | type Rectangle struct { | ||
Line 20: | Line 21: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Pointers as self | |||
Keep in mind that go parameters are value types and will contain copies of your object.<br> | Keep in mind that go parameters are value types and will contain copies of your object.<br> | ||
Line 66: | Line 69: | ||
</blockquote><!-- Local Types --> | </blockquote><!-- Local Types --> | ||
= | = Method Overloading = | ||
<blockquote> | <blockquote> | ||
Not supported in go. | |||
</blockquote><!-- Function Overloading --> | |||
</blockquote><!-- |
Latest revision as of 15:42, 6 June 2022
While Go is not an OOP language, it lets you bind methods to any type.
This is most common with structs, but any type is supported
Adding Methods
Basics
type Rectangle struct { width int height int } func (a Rectangle) Area() int { return a.width * a.height } func main() { rect := Rectangle{width: 10, height: 10} fmt.Println(rect.Area() == 100) }Pointers as self
Keep in mind that go parameters are value types and will contain copies of your object.
If working with large objects, it may be more efficient to refer to the object as a pointer.type Rectangle struct { width int height int } func (a *Rectangle) Area() int { // manually de-reference pointer 'a' to get it's value return (*a).width * (*a).height } func (a *Rectangle) Perimeter() int { // go knows you are working with a pointer, you can skip the '(*a)' return (a.width * 2) + (a.height * 2) } func main() { rect := Rectangle{5, 5} fmt.Println(rect.Area()) }
Local Types
You can also create local wrapper types for other types,
which lets you add methods, only in a specific localized scopetype Int int func (i Int) Double() Int { return i * 2 } func main() { five := Int(5) fmt.Println(five.Double() == 10) }
Method Overloading
Not supported in go.