Skip to content

Instantly share code, notes, and snippets.

@miku
Last active August 29, 2015 14:21
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 miku/8ed83c4919e93d328657 to your computer and use it in GitHub Desktop.
Save miku/8ed83c4919e93d328657 to your computer and use it in GitHub Desktop.
Example for pointer receiver.
package main
import (
"fmt"
"log"
)
// IntQueue is a FIFO queue.
type IntQueue struct {
queue []int
}
// Push an element onto the queue.
func (q *IntQueue) Push(i int) {
// mutation
q.queue = append(q.queue, i)
}
// Pop from the queue.
func (q *IntQueue) Pop() int {
if len(q.queue) < 1 {
log.Fatal("pop from an empty queue")
}
i := len(q.queue) - 1
v := q.queue[i]
// mutation
q.queue = q.queue[:i]
return v
}
func (q *IntQueue) Size() int {
return len(q.queue)
}
func main() {
q := &IntQueue{}
q.Push(100)
q.Push(200)
fmt.Println(q)
q.Pop()
fmt.Println(q)
q.Pop()
fmt.Println(q)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment