golang notes(2)
作者:互联网
1, IDE (goland)
One may need 'jetbrains-agent-latest.zip':
链接: https://pan.baidu.com/s/1Ze1TUhByRNX7BkAU8mNpIw 提取码: dx2k
2, defer
<Defer, Panic, and Recover> is an excellent doc: https://www.cnblogs.com/kaid/p/9698477.html
3, Execise: Slices
package main
import (
//"fmt"
"golang.org/x/tour/pic"
)
func Pic(dx, dy int) [][]uint8 {
var p [][]uint8 = make([][]uint8, dx)
for i := 0; i < dx; i++ {
p[i] = make([]uint8, dy)
for j :=0; j < dy; j++ {
p[i][j] = uint8(i*j)
}
}
return p
}
func main() {
//fmt.Println(Pic(16, 16))
pic.Show(Pic)
}
The result output looks like:
IMAGE:iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAACAAElEQVR42uy9B3jUVfb/P7r21dVVdy1r74o1o
//omitted
348mQMB8NVXuvpRP57MgQD4+mtd/agfT+ZAAPz1r7r6UT+ezIEA+OYbXf2oH0/mQAD87W+6+lE/nsyBAPj2W139qB9P5kAAfPedrn7UjydzIADu3dPVj/rxZI7/HwAA//9vd4RSMvSyIgAAAABJRU5ErkJggg==
From here(https://stackoverflow.com/questions/18553246/tour-golang-org36-the-functionality-implemented-by-pic-show), we can see the implementation of pic.Show:
Funny thing is it ends up printing the string "IMAGE:" followed by the base64 encoded string. Seems that play.golang.org parses the output converting this to an img
tag. Try the following example: http://play.golang.org/p/RZPqp164eS
Since the program needs import a 3rd-party package: golang.org/x/tour/pic, make sure to create a go.mod first:
(07:30 dabs@CNU1343VF8 slices) > ls
go.mod slices slices.go
(07:30 dabs@CNU1343VF8 slices) > cat go.mod
module slices
(07:30 dabs@CNU1343VF8 slices) > go build slices.go
go: finding module for package golang.org/x/tour/pic
go: found golang.org/x/tour/pic in golang.org/x/tour v0.0.0-20200508155540-0608babe047d
4, Execise: Maps
package main
import (
//"fmt"
"strings"
"golang.org/x/tour/wc"
)
func main() {
wc.Test(WordCount)
}
func WordCount(s string) map[string]int {
m := make(map[string]int)
tokens := strings.Fields(s)
for _, word := range tokens {
v, ok := m[word]
if ok {
m[word] = v + 1
} else {
m[word] = 1
}
}
return m
}
Output looks like:
PASS
f("I am learning Go!") =
map[string]int{"Go!":1, "I":1, "am":1, "learning":1}
PASS
f("The quick brown fox jumped over the lazy dog.") =
map[string]int{"The":1, "brown":1, "dog.":1, "fox":1, "jumped":1, "lazy":1, "over":1, "quick":1, "the":1}
PASS
f("I ate a donut. Then I ate another donut.") =
map[string]int{"I":2, "Then":1, "a":1, "another":1, "ate":2, "donut.":2}
PASS
f("A man a plan a canal panama.") =
map[string]int{"A":1, "a":2, "canal":1, "man":1, "panama.":1, "plan":1}
5, Execise: Fibonacci closures
package main
import (
"fmt"
)
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
func fibonacci() func() int {
var fibs []int
return func() int {
var v int
i := len(fibs)
switch {
case i == 0 || i == 1:
v = 1
fibs = append(fibs, v)
default:
v = fibs[i-1] + fibs[i-2]
fibs = append(fibs, v)
}
return v
}
}
Output looks like:
1
1
2
3
5
8
13
21
34
55
标签:string,int,notes,fibs,golang,go,org 来源: https://blog.csdn.net/jeffyko/article/details/106291951