Created
November 1, 2013 00:32
-
-
Save genghisjahn/7259432 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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