go的安装,IDE使用的jetBrains的Gogland,全部安装完后在IDE中的File中设置setting配置好goroot和gopath;
使用的书籍是《Go语言程序设计》,在windows的cmd中运行;
第一个例子
package main
import(
"fmt"
"os"
"strings"
)
func main() {
who :="world!"
if len(os.Args)>1{
who=strings.Join(os.Args[1:],"")
}
fmt.Println("Helllo",who)
}
第二个例子
package main
import (
"fmt"
"os"
"path/filepath"
"log"
)
var bigDigits=[][]string{
{" 000 "},
{" 1 "},
{" 2 "},
{" 3 "},
{" 4 "},
{" 5 "},
{" 6 "},
{" 7 "},
{" 8 "},
{" 9 "},
}
func main() {
if len(os.Args)==1{
fmt.Printf("usage:%s<whole-number>\n",filepath.Base(os.Args[0]))
os.Exit(1)
}
stringOfDigits :=os.Args[1]
for row :=range bigDigits[0]{
line :=""
for column:=range stringOfDigits{
digit:=stringOfDigits[column]-‘0‘
if 0<=digit&&digit<=9{
line+=bigDigits[digit][row]+" "
}else {
log.Fatal("invalid whole number")
}
}
fmt.Println(line)
}
}
1.5 栈-自定义类型和其方法
src\stacker\stack\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) IsEmpty() bool {
if len(stack) == 0 {
return false
}
return true
}
func (stack *Stack) Push (x interface{}) {
*stack = append(*stack,x)
}
func (stack Stack) Top() (interface{},error) {
if len(stack) == 0 {
return nil,errors.New("can‘t Top en empty stack")
}
return stack[len(stack)-1],nil
}
func (stack *Stack) Pop() (interface{},error) {
theStack := *stack
if len(theStack) == 0{
return nil, errors.New("Can‘t pop an empty stack")
}
x := theStack[len(theStack) - 1]
*stack = theStack[:len(theStack) - 1]
return x,nil
}
stacker\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.Pop()
if err != nil {
break
}
fmt.Println(item)
}
}
原文:http://www.cnblogs.com/haungxiaonian/p/6401569.html