go的安裝,IDE使用的jetBrains的Gogland,所有安裝完後在IDE中的File中設置setting配置好goroot和gopath;git
使用的書籍是《Go語言程序設計》,在windows的cmd中運行;windows
第一個例子app
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 mainimport ( "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) }}