Last active
August 29, 2015 14:21
-
-
Save miku/8ed83c4919e93d328657 to your computer and use it in GitHub Desktop.
Example for pointer receiver.
This file contains 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" | |
"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