Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// PointerTest project main.go
package main
import (
"fmt"
)
func main() {
//http://www.golang-book.com/9
//We create two person objects and assign them names.
Bob := Person{"Bob"}
Frank := Person{"Frank"}
//Each Person object has a Talk method that accepts a pointer to type Person
//See below.
Bob.Talk(&Frank)
Frank.Talk(&Bob)
//Bob and Frank talk to each other by using the method and a pointer to the Person they are talking to.
//Marty is an android. It has an embedded type Person, with one extra field, Model
Marty := new(Android)
Marty.Name = "Marty"
Marty.Model = "T1000"
Marty.Talk(&Bob)
//Marty can talk to Bob using the Talk method, the same way Frank could.
//Arnold is an android, same as Marty
Arnold := Android{Person{"Arnold"}, "T1001"}
//Arnold.Beep(&Marty) //This is an error.
Marty.Beep(&Arnold)
/*
So, Marty can Beep at Arnold, but Arnold can't beep at Marty!
(Maybe one of them is running Windows RT, <snort>)
The reason is, Marty was created with the new keyword, which returns a...pointer.
That's right! Arnold is a variable of type Android, but
Marty is a variable of type pointer to Android.
From documentation...
This allocates memory for all the fields,
sets each of them to their zero value and ***returns a pointer.***
Since the Beep method accepts pointers and not structs, we can just pass Marty as is,
since it already is a pointer.
No need to de-reference with *
*/
Arnold.Beep(Marty)
//If we want to get the value of Marty, we de-ref with the *.
MartyValue := *Marty
MartyValue.Talk(&Bob)
}
type Person struct {
Name string
}
type Android struct {
Person
Model string
}
func (p *Person) Talk(TalkingTo *Person) {
fmt.Printf("%v said, 'Hello there, %v.'\n", p.Name, TalkingTo.Name)
}
func (a *Android) Beep(BeepAt *Android) {
fmt.Printf("%v beeped, 101010100001 at %v\n", a.Name, BeepAt.Name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.