From a8ba753c92d83f63dc7a4895320aa4c48dc5a733 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 8 Dec 2024 19:10:14 -0600 Subject: [PATCH] Add Add A Method To A Struct as a Go TIL --- README.md | 3 +- go/add-a-method-to-a-struct.md | 70 ++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 go/add-a-method-to-a-struct.md diff --git a/README.md b/README.md index 9ae70b9..adba594 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/go/add-a-method-to-a-struct.md b/go/add-a-method-to-a-struct.md new file mode 100644 index 0000000..6bc2782 --- /dev/null +++ b/go/add-a-method-to-a-struct.md @@ -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)