美文网首页
Go 语言程序设计(3)

Go 语言程序设计(3)

作者: hlemon | 来源:发表于2019-03-24 19:35 被阅读0次

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.Top()
        if err != nil {
            break
        }
        fmt.Println("top", item)
    }
}

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) Push(x interface{}) {
    *stack = append(*stack, x)
}

func (stack *Stack) Top() (interface{}, error) {
    theStack := *stack
    if len(theStack) == 0 {
        return nil, errors.New("can't Top en empty stack")
    }
    x := theStack[0]
    *stack = theStack[1:len(theStack)]
    return x, nil
}

func (stack *Stack) Pop() (interface{}, error) {
    theStack := *stack
    if len(theStack) == 0 {
        return nil, errors.New("can't Pop en empty stack")
    }
    x := theStack[len(theStack) - 1]
    *stack = theStack[:len(theStack) - 1]
    return x, nil
}

知识点:

  • go 内置基础类型:
    • 布尔类型: bool
    • 整型: int8byteint16intuintuintptr
    • 浮点点类型: float32float64
    • 复数类型: complex64complex128
    • 字符: string
    • 字符类型: rune
    • 错误类型: error
  • go 语言没有类的概念,只有类型和值
  • 接口也是一种类型,接口是抽象的,因此不可以实例化
  • 空接口(没有定义方法的接口)用 interfae {} 表示
  • 本地包导入会首先搜索 GOPATH,然后再搜搜 GOROOT 所定义的路径
  • 本地包必须保存在一个与包名同名的目录下
  • len()cap() 方法的区别():
    • len() 可以用来查看数组或切片的长度
    • cap() 可以用来查看数组或切片的容量
  • nil 是用来表示空指针(空引用),表示指向为空的指针或者引用值为空的引用
  • go 语言通过在类型前加一个 星号* 来声明指针(指针是一个保存了另一个值的内存地址的变量)

切片Slice:

  • 其本身并不是数组,它指向底层的数组
  • 作为变长数组的替代方案,可以关联底层数组的局部或全部
  • 为引用类型
  • 可以直接创建或从底层数组获取生成
  • 使用 len() 获取元素个数,cap() 获取容量
  • 一般使用 make 创建
  • 如果多个slice指向相同底层数组,其中一个的值改变会影响全部

相关文章

网友评论

      本文标题:Go 语言程序设计(3)

      本文链接:https://www.haomeiwen.com/subject/flbuvqtx.html