Created
June 11, 2014 15:43
-
-
Save Quantisan/519d5f3aee5949ce49ca to your computer and use it in GitHub Desktop.
Defining methods on values or pointers
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
package main | |
import ( | |
"fmt" | |
) | |
type rectPointer struct { | |
width int | |
height int | |
} | |
func (r *rectPointer) Print() { | |
fmt.Printf("width: %v, height: %v\n", r.width, r.height) | |
} | |
func (r *rectPointer) set(w, h int) { | |
r.width = w | |
r.height = h | |
} | |
type rectValue struct { | |
width int | |
height int | |
} | |
func (r rectValue) Print() { | |
fmt.Printf("width: %v, height: %v\n", r.width, r.height) | |
} | |
func (r rectValue) set(w, h int) { | |
r.width = w | |
r.height = h | |
} | |
func main() { | |
fmt.Println("Pointer") | |
rp := rectPointer{width: 10, height: 5} | |
rp.Print() | |
rp.set(100, 100) | |
rp.Print() | |
// Pointer | |
//width: 10, height: 5 | |
//width: 100, height: 100 | |
fmt.Println() | |
fmt.Println("Value") | |
rv := rectValue{width: 10, height: 5} | |
rv.Print() | |
rv.set(100, 100) | |
rv.Print() | |
// Value | |
//width: 10, height: 5 | |
//width: 10, height: 5 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment