Skip to content

Instantly share code, notes, and snippets.

@Quantisan
Created June 11, 2014 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Quantisan/519d5f3aee5949ce49ca to your computer and use it in GitHub Desktop.
Save Quantisan/519d5f3aee5949ce49ca to your computer and use it in GitHub Desktop.
Defining methods on values or pointers
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