mirror of
https://github.com/bootdotdev/fcc-learn-golang-assets.git
synced 2025-12-10 15:21:18 +00:00
first
This commit is contained in:
47
course/11-pointers/exercises/5-pointer_receiver/readme.md
Normal file
47
course/11-pointers/exercises/5-pointer_receiver/readme.md
Normal file
@@ -0,0 +1,47 @@
|
||||
# Pointer Receivers
|
||||
|
||||
A receiver type on a method can be a pointer.
|
||||
|
||||
Methods with pointer receivers can modify the value to which the receiver points. Since methods often need to modify their receiver, pointer receivers are *more common* than value receivers.
|
||||
|
||||
## Pointer receiver
|
||||
|
||||
```go
|
||||
type car struct {
|
||||
color string
|
||||
}
|
||||
|
||||
func (c *car) setColor(color string) {
|
||||
c.color = color
|
||||
}
|
||||
|
||||
func main() {
|
||||
c := car{
|
||||
color: "white",
|
||||
}
|
||||
c.setColor("blue")
|
||||
fmt.Println(c.color)
|
||||
// prints "blue"
|
||||
}
|
||||
```
|
||||
|
||||
## Non-pointer receiver
|
||||
|
||||
```go
|
||||
type car struct {
|
||||
color string
|
||||
}
|
||||
|
||||
func (c car) setColor(color string) {
|
||||
c.color = color
|
||||
}
|
||||
|
||||
func main() {
|
||||
c := car{
|
||||
color: "white",
|
||||
}
|
||||
c.setColor("blue")
|
||||
fmt.Println(c.color)
|
||||
// prints "white"
|
||||
}
|
||||
```
|
||||
Reference in New Issue
Block a user