Golang 之 面向物件type ,擴張系統已有型別
阿新 • • 發佈:2018-11-12
目錄
main包
package main
import (
. "../../queue"
. "fmt"
)
func main() {
q := Queue{1,2,3,4}
q.Push(5)
q.Pop()
q.Pop()
q.Pop()
Println(q.IsEmpty())
}
- queue包
Go語言中可以通過type關鍵字宣告型別,如type StrSlice []string 將[]string(string型別的切片)宣告為StrSlice 型別
package queue
type Queue []int
func (q *Queue) Push(v int) {
*q = append(*q, v)
}
func (q *Queue) Pop() int {
head := (*q)[0]
*q = (*q)[1:]
return head
}
func (q *Queue) IsEmpty() bool {
return len(*q) == 0
}