Go language learning-package usage

Source: Internet
Author: User

Import a public package using import or a custom package similar to include in C. According to the tutorial, write a package that judges whether a number is an even number.

Run mkdir even in the current directory and enter the directory. Write the following code to VI even. Go:

package even func Even(a int ) bool {    state := false    if a%2 == 0 {        state=  true    }    return state}

Then write a test program:

package
main
  import
"./even"
  func
main() {
     a:=
3
     if
even.Even(a) {
         println("is
even")
     }else{          println("not
a even")
     } }

Note: 1. Add even before the introduced even function; 2. the first letter of the function or variable for external use must be capitalized.

Go implements a stack:

package main  type stack struct {    top int     mLength int    data [10]int} func push(s *stack, key int ) {    if s.top +1 == 10{        return     }    s.data[s.top+1] = key    s.top ++    return } func pop(s *stack ) int {    if s.top == 0 {        return -1    }    key := s.data[s.top-1]     s.top --    return key} func get(s stack ) int {    if(s.top == 0){        return -1    }    return s.data[s.top-1]}   func main(){    var s stack    push(&s,25)    push(&s,14)    println(get(s)) }

Package format:

package stack type Stack struct {    top int     mLength int    data [10]int} func (s *Stack)Push( key int ) {    if s.top +1 == 10{        return     }    s.data[s.top+1] = key    s.top ++    return } func (s * Stack )Pop( ) int {    if s.top == 0 {        return -1    }    key := s.data[s.top-1]     s.top --    return key} func (s * Stack)Get( ) int {    if(s.top == 0){        return -1    }    return s.data[s.top-1]} 

Test_stack.go

package main  import "./stack" func main(){    var s stack.Stack    s.Push(1)    s.Push(2)    println(s.Get())}

Original blog address: http://www.fuxiang90.com/2012/08/go-%E8%AF%AD%E8%A8%80%E5%AD%A6%E4%B9%A0-%E5%8C%85%E7%9A%84%E7%94%A8%E6%B3%95/

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.