1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 15:18:01 +00:00

Add Add A Method To A Struct as a Go TIL

This commit is contained in:
jbranchaud
2024-12-08 19:10:14 -06:00
parent 77f3c6a43d
commit a8ba753c92
2 changed files with 72 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1531 TILs and counting..._
_1532 TILs and counting..._
---
@@ -398,6 +398,7 @@ _1531 TILs and counting..._
### Go
- [Access Go Docs Offline](go/access-go-docs-offline.md)
- [Add A Method To A Struct](go/add-a-method-to-a-struct.md)
- [Build For A Specific OS And Architecture](go/build-for-a-specific-os-and-architecture.md)
- [Combine Two Slices](go/combine-two-slices.md)
- [Do Something N Times](go/do-something-n-times.md)

View File

@@ -0,0 +1,70 @@
# Add A Method To A Struct
Given a `struct` in Go, we can attach a method to that struct. Put another way,
we can define a method whose receiver is that struct. Then with an instance of
that struct, we can call the method.
Let's say we are modeling a turtle that can move around a 2D grid. A turtle has
a heading (the direction it is headed) and a location (its current X,Y
coordinate).
```go
type Heading string
const (
UP Heading = "UP"
RIGHT Heading = "RIGHT"
DOWN Heading = "DOWN"
LEFT Heading = "LEFT"
)
type Turtle struct {
Direction Heading
X int
Y int
}
```
We can then add a method like so by specifying the receiver as the first part
of the declaration:
```go
func (turtle *Turtle) TurnRight() {
switch turtle.Direction {
case UP:
turtle.Direction = RIGHT
case RIGHT:
turtle.Direction = DOWN
case DOWN:
turtle.Direction = LEFT
case LEFT:
turtle.Direction = UP
}
}
```
The receiver is a pointer to a `Turtle`. The method is called `TurnRight`.
There are no parameters or return values.
Here are a sequence of calls to demonstrate how it works:
```go
func main() {
turtle := Turtle{UP, 5, 5}
fmt.Println("Turtle Direction:", turtle.Direction)
//=> Turtle Direction: UP
turtle.TurnRight()
fmt.Println("Turtle Direction:", turtle.Direction)
//=> Turtle Direction: RIGHT
turtle.TurnRight()
fmt.Println("Turtle Direction:", turtle.Direction)
//=> Turtle Direction: DOWN
}
```
[source](https://go.dev/tour/methods/1)