This is a creation in Article, where the information may have evolved or changed.
One, custom stacks
Package Stackimport"Errors"type Stack []Interface{}func (Stack*stack) Pop (Interface{}, error) {thestack:= *StackifLen (thestack) = =0 { returnNil, errors. New ("can ' t pop () an empty stack")} x:= Thestack[len (Thestack)-1] *stack = Thestack[:len (thestack)-1] returnx, Nil}func (Stack*stack) Push (xInterface{}) { *stack = Append (*stack, x)} Func (Stack*stack) Top () (Interface{}, error) { ifLen (stack) = =0 { returnNil, errors. New ("Cat ' t Top () an empty stack") } returnStack[len (Stack)-1], Nil}func (Stack stack) Cap ()int { returnCap (Stack)}func (stack stack) Len ()int { returnlen (Stack)}func (stack stack) IsEmpty ()BOOL { returnLen (stack) = =0}
As a package, the first is the declaration, if it is the main package, then it is to declare a main function, and can run independently.
The package then defines the type of stack said interface, and defines a number of stack-specific methods.
About Interface,interface is a group of methods, in a interface, can contain a series of concrete methods.
All of the types in Golang implement empty interface, so these interface can be stored in a stack.
Two, interface
In the Go language, an interface is a custom type that declares one or more method signatures, and the interface is completely abstract and therefore cannot be instantiated. However, you can create a variable of its type thing interface, which can be assigned to any value that satisfies the actual type of the interface type.
When defining interface, the interface name convention ends with ER.
By defining and using interface, you can flexibly add types, methods, and interfaces without changing the inheritance tree.