Go - strings

寫到 leetcode 459. Repeated Substring Pattern 時,看了討論區發現 strings.Repeat(s string, count int) 這個好用的函式,所以決定開一篇文用以記錄 Golang strings 裏面值得記起來的函式或用法,方便自己複習。

Repeat

重複傳入的字串指定次數

  package main
  import (
    "fmt"
    "strings"
  )

  func main() {
    fmt.Println("ba" + strings.Repeat("na", 2))
    // banana
  }

Fields

將字串以空格為基準進行切割,回傳字串陣列

  package main
  import (
    "fmt"
    "strings"
  )

  func main() {
	  fmt.Printf("Fields are: %q", strings.Fields("  foo bar  baz   "))
    // Fields are: ["foo" "bar" "baz"]
  }

Go - Convert between string & int & rune

package main

import (
	"fmt"
	"strconv"
)

func main() {
	n := 10
	str := strconv.Itoa(n) // convert to string
	for _, val := range str {
		fmt.Printf("%T  %v\n", val, val)
		fmt.Printf("%T  %v\n", int(val)-'0', int(val)-'0') // convert rune/int32 to int
	}

	n2, err := strconv.Atoi(str) // convert string to int
	if err == nil {
		fmt.Printf("%T  %v\n", n2, n2)
	}
}

Go - sort

sortGo 裏面數一數二常用的package,下面介紹三種函式。

Ints

最基本的整數由小到大排序。

package main

import (
	"fmt"
	"sort"
)

func main() {
	s := []int{5, 2, 6, 3, 1, 4} // unsorted
	sort.Ints(s)
	fmt.Println(s)
  // [1 2 3 4 5 6]
}

Strings

最基本的字串由小到大排序。

package main

import (
	"fmt"
	"sort"
)

func main() {
	s := []string{"Go", "Bravo", "Gopher", "Alpha", "Grin", "Delta"}
	sort.Strings(s)
	fmt.Println(s)
  // [Alpha Bravo Delta Go Gopher Grin]
}

Slice

依照給訂的規則來排序,並不保證 stable ,如果想要確保 stable ,可以用另一個函式叫做 SliceStable

import (
	"fmt"
	"sort"
)

func main() {
	people := []struct {
		Name string
		Age  int
	}{
		{"Gopher", 7},
		{"Alice", 55},
		{"Vera", 24},
		{"Bob", 75},
	}
	sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
	fmt.Println("By name:", people)
  // By name: [{Alice 55} {Bob 75} {Gopher 7} {Vera 24}]

	sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
	fmt.Println("By age:", people)
  // By age: [{Gopher 7} {Vera 24} {Alice 55} {Bob 75}]
}

Go - Convert int to string

An integer can be converted to string by Itoa function which is in strconv library.
Example :

import (
	"fmt"
	"reflect"
	"strconv"
)

func main() {
	nums1 := 10
	fmt.Println(nums1, reflect.TypeOf(nums1))
	str := strconv.Itoa(nums1)
	fmt.Println(str, reflect.TypeOf(str))
}

unknown feature `proc_macro_span_shrink`

I encounter below error when run command anchor build.

error[E0635]: unknown feature `proc_macro_span_shrink`

Solution is downgrading proc-macro2 to 1.0.43 :

cargo update -p proc-macro2 --precise 1.0.43

Reference