"Go Language Programming" study (IV)

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.