Go 语言程序设计(3)

2019-03-24  本文已影响0人  hlemon

stacker.go 示例代码:

package main

import (
    "fmt"
    "stacker/stack"
)

func main() {
    var haystack stack.Stack
    haystack.Push("hay")
    haystack.Push(-15)
    haystack.Push([]string{"pin", "clip", "needle"})
    haystack.Push(81.52)

    for {
        item, err := haystack.Top()
        if err != nil {
            break
        }
        fmt.Println("top", item)
    }
}

stack.go 示例代码:

package stack

import "errors"

type Stack []interface {}

func (stack Stack) Len() int {
    return len(stack)
}

func (stack Stack) Cap() int {
    return cap(stack)
}

func (stack *Stack) Push(x interface{}) {
    *stack = append(*stack, x)
}

func (stack *Stack) Top() (interface{}, error) {
    theStack := *stack
    if len(theStack) == 0 {
        return nil, errors.New("can't Top en empty stack")
    }
    x := theStack[0]
    *stack = theStack[1:len(theStack)]
    return x, nil
}

func (stack *Stack) Pop() (interface{}, error) {
    theStack := *stack
    if len(theStack) == 0 {
        return nil, errors.New("can't Pop en empty stack")
    }
    x := theStack[len(theStack) - 1]
    *stack = theStack[:len(theStack) - 1]
    return x, nil
}

知识点:

切片Slice:

上一篇 下一篇

猜你喜欢

热点阅读