0%

Go常用函数

Go 常用函数

排序

  • sort.Ints(arr)

数组

  • arr = append(arr, []int{1,2,3})

字符串

strconv 包

  • string 转 int int, err := strconv.Atoi(string)
  • string 转 int64 int64, err := strconv.ParseInt(string, 10, 64)
  • int 转 string string := strconv.Itoa(int)
  • int64 转 string string := strconv.FormatInt(int64,10)

strings 包

  • func Contains(s, substr string) bool
  • func Count(s, sep string) int
  • func Fields(s string) []string
  • func HasPrefix(s, prefix string) bool
  • func Index(s, sep string) int
  • func Join(a []string, sep string) string

bytes 包同理,区别在于参数换成了 []byte

bytes.Buffer

  • buf.Write()
  • buf.WriteRune
  • buf.String()

代码示例:

1
2
3
4
5
6
7
8
9
func main() {
var buf bytes.Buffer
s := string("吴兴宇")

for _, val := range s {
buf.WriteRune(val)
}
fmt.Println(buf.String())
}
  • bytes.Buffer类型用于字节slice的缓存。一个Buffer开始是空的,但是随着string、byte或[]byte等类型数据的写入可以动态增长,一个bytes.Buffer变量并不需要初始化,因为零值也是有效的。
  • 当向bytes.Buffer添加任意字符的UTF8编码时,最好使用bytes.Buffer的WriteRune方法,但是WriteByte方法对于写入类似’[‘和’]’等ASCII字符则会更加有效。

容器

list(双向)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
type Element
func (e *Element) Next() *Element
func (e *Element) Prev() *Element
type List
func New() *List
func (l *List) Back() *Element // 返回最后一个元素
func (l *List) Front() *Element // 返回第一个元素
func (l *List) Init() *List // 链表初始化
func (l *List) InsertAfter(v interface{}, mark *Element) *Element // 在某个元素前插入
func (l *List) InsertBefore(v interface{}, mark *Element) *Element // 在某个元素后插入
func (l *List) Len() int // 返回链表长度
func (l *List) MoveAfter(e, mark *Element) // 把e元素移动到mark之后
func (l *List) MoveBefore(e, mark *Element) // 把e元素移动到mark之前
func (l *List) MoveToBack(e *Element) // 把e元素移动到队列最后
func (l *List) MoveToFront(e *Element) // 把e元素移动到队列最头部
func (l *List) PushBack(v interface{}) *Element // 在队列最后插入元素
func (l *List) PushBackList(other *List) // 在队列最后插入接上新队列
func (l *List) PushFront(v interface{}) *Element // 在队列头部插入元素
func (l *List) PushFrontList(other *List) // 在队列头部插入接上新队列
func (l *List) Remove(e *Element) interface{} // 删除某个元素

使用示例:

1
2
3
4
5
6
7
queue := list.New()	// 创建一个 list
queue.PushBack(&postion{x, y}) // 在链表尾部插入一个结构体指针
for queue.Len() != 0 {
element := queue.Front() // 取出链表头部的元素,是 Element 类型
pos := element.Value.(*postion) // Element.Value 取出值,是 interface{} 类型,通过断言转型成 *position
queue.Remove(element) // 删除指定元素, Element 类型
}

heap

ring