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\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.bubuko.com/infodetail-1946315.html