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/