Add Slice push, pop, unshift, shift, json

tags/v1.1.0 v1.1.0
Stanly 3 years ago
parent c015dceee0
commit 9db4b3652f

@ -0,0 +1,55 @@
package types
import (
"encoding/json"
)
type Slice []interface{}
// Push 後堆
func (slice *Slice) Push(value interface{}) {
*slice = append(*slice, value)
}
// Pop 後取
func (slice *Slice) Pop() (value interface{}) {
length := len(*slice)
if length > 0 {
value = (*slice)[length-1]
*slice = append((*slice)[:length-1])
}
return value
}
// Unshift 前堆
func (slice *Slice) Unshift(value interface{}) {
*slice = append(Slice{value}, *slice...)
}
// Shift 前取
func (slice *Slice) Shift() (value interface{}) {
length := len(*slice)
if length > 0 {
value = (*slice)[0]
*slice = (*slice)[1:length]
}
return value
}
// JSON 取得json
func (slice *Slice) JSON() ([]byte, error) {
bs, err := json.Marshal(slice)
if err != nil {
return nil, err
}
return bs, nil
}
// MustJSON 強制取得json
func (slice *Slice) MustJSON() []byte {
bs, _ := slice.JSON()
return bs
}
Loading…
Cancel
Save