golangref.txt 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. # golang reference
  2. # download - https://go.dev/dl/
  3. # download and install - https://go.dev/doc/install
  4. # to install the toolset, download and run the installer from golang.org/dl
  5. # tutorial: get started with go - https://go.dev/doc/tutorial/getting-started
  6. # tutorial: create a go module - https://go.dev/doc/tutorial/create-module
  7. # tutorial: using go modules - https://go.dev/blog/using-go-modules
  8. # tutorial: gonum matrix -
  9. # https://pkg.go.dev/gonum.org/v1/gonum/mat?utm_source=godoc
  10. # tutorial: The gonum numerical computing packages -
  11. # https://www.gonum.org/post/intro_to_gonum/
  12. # data format: https://pkg.go.dev/fmt#Scanf
  13. # awesome go: https://awesome-go.com/
  14. # go-to guide: https://yourbasic.org/golang/#cheat-sheets
  15. # staticcheck: https://staticcheck.dev/docs/getting-started/
  16. # math/bits: https://pkg.go.dev/math/bits
  17. # lean go with tests: https://quii.gitbook.io/learn-go-with-tests/
  18. # online resources:
  19. Tutorials: https://go.dev/doc/tutorial/
  20. The Official Go Website
  21. The Go Tour
  22. go version # print version
  23. go help # list of tools
  24. go help doc # documentation tool
  25. go help list # list tool
  26. go env # environment variables
  27. go env GOPROXY GOROOT GOCACHE # specific environment variables
  28. go env --json | jq .
  29. go env --json | jq -r '.GOPROXY'
  30. # GOPATH /* path for installed executable binaries - $GOPATH/bin */
  31. To find out where $GOPATH is, run
  32. $ go env GOPATH
  33. /home/user/go /* default GOPATH */
  34. To change the default GOPATH, edit .bashrc
  35. export GOPATH="$HOME/.gopath" /* change GOPATH */
  36. export PATH=$GOPATH/bin:$PATH /* add GOPATH to PATH */
  37. $ go env GOPATH /* source .bashrc */
  38. /home/user/.gopath
  39. # installing program/package with go install
  40. The 'go install' command behaves almost identically to 'go build', but instead of
  41. leaving the executable in the current directory, or a directory specified by the -o
  42. flag, it places the executable into the '$GOPATH/bin' directory.
  43. To find where your $GOPATH directory is located, run the following command:
  44. $ go env GOPATH
  45. The output you receive will vary, but the default is the 'go' directory inside of
  46. your $HOME directory: /home/user/go
  47. Since 'go install' will place generated executables into a sub-directory of '$GOPATH'
  48. named 'bin', this directory must be added to the '$PATH' environment variable.
  49. With the '$GOPATH/bin' directory set up, move back to your project source directory and
  50. run the install command:
  51. $ go install
  52. This will build your binary and place it in '$GOPATH/bin'. To test this, run the
  53. following:
  54. $ ls $GOPATH/bin /* list the contents of $GOPATH/bin */
  55. # formating program in golang
  56. go fmt filename.go
  57. # list files whose formatting differs from gofmt's
  58. gofmt -l
  59. # code format: simplify and write result to (source) file
  60. gofmt -s -w
  61. # 'gofmt' plus fix imports and write result to (source) file
  62. goimports -w
  63. # mechanical source transformation
  64. # rewrite code
  65. gofmt -r ...
  66. # rewrite rule: pattern -> replacement
  67. # [pattern] & [replacement] must be valid go expressions
  68. gofmt -r 'bytes.Compare(a, b) == 0 -> bytes.Equal(a, b)'
  69. # go documentation
  70. # view full documentation for the strings package
  71. go doc -all strings | less
  72. # view documentation for the strings.Replace function
  73. go doc strings.Replace
  74. # show source code for strings.Replace
  75. go doc -src strings.Replace | less
  76. # offline http server that includes all go documentation, tutorial and books
  77. go install golang.org/x/tools/cmd/godoc@latest
  78. godoc -http=:6060 & # run go documentation server (offline) :6060
  79. open http://localhost:6060
  80. pkill godoc
  81. # dependency inspection
  82. # list all packages the project depend on (direct & indirect)
  83. go list all
  84. # introspect Go packages and their interdependencies
  85. go list -f '{{ join .Imports "\n" }}' # directly import packages the project depend on
  86. # list all modules
  87. go list -m all
  88. # list outdated direct modules
  89. go list -f '{{if and (not .Indirect) .Update}}{{.}}{{end}}' -u -m all
  90. # use depth for different visualization
  91. depth -explain regexp gtoken # explain why specific package (regexp) is included into the project
  92. # check the source code is compliant with the import packages license
  93. golicense -verbose -license ../../.golicense.json .bin/gtoken
  94. # build
  95. # list supported architectures and OS for Go builder
  96. go tool dist list
  97. # build linux arm64 executable
  98. GOOS=linux GOARCH=amd64 go build -o=.bin/$GOOS_$GOARCH/app .
  99. # inspect linker flags
  100. go tool link -help
  101. # embed version info into build
  102. export VERSION=$(git describe --tags --always --dirty)
  103. export COMMIT=$(git rev-parse --short HEAD)
  104. export BRANCH=$(git rev-parse --abbrev-ref HEAD)
  105. export DATE=$(date +%FT%T%z)
  106. go build -ldflags "-X main.Version=${VERSION} \
  107. -X main.GitCommit=${COMMIT} \
  108. -X main.GitBranch=${BRANCH} \
  109. -X main.BuildDate=${DATE}" -o .bin/app
  110. $ .bin/app --version # to display above info
  111. # static builds
  112. # disable cgo, unless you need to interoperate with C libraries
  113. # most likely - you do not need it
  114. CGO_ENABLED=0
  115. # Go linker flags
  116. # -s: omit the symbol table and debug information
  117. # -w: omit the DWARF symbol table
  118. go build -ldflags='-s -w' -o=.bin/app
  119. # build tags
  120. # build (linux and arm64)
  121. package app # +build linux, arm64
  122. # build/test only if '--tags=integration' is provided
  123. package app
  124. import "testing" # +build integration
  125. # test
  126. go test # run tests
  127. go test -cover # run tests with code coverage
  128. go test -race # test with race condition
  129. # tests/mock generation
  130. go install github.com/cweill/gotests/gotests@latest
  131. gotests # generate table driven tests
  132. gotests -all -w main.go
  133. mockery # generate mock for Go interfaces
  134. mockery -all -inpkg
  135. go test -v -cover .
  136. richgo test -v -cover . # same as above but with colors
  137. # benchmark
  138. go test -run=^$ -bench=. ./... # run benchmark only, skipping tests
  139. go test -bench=. | tee v1.txt # output to file v1.txt and also terminal display
  140. go test -bench=. | tee v2.txt # output to file v2.txt and also terminal display
  141. benchcmp v1.txt v2.txt # compare benchmark results
  142. # static analysis
  143. # inspect vet tool
  144. go tool vet help
  145. go vet
  146. # report unchecked errors
  147. errcheck
  148. # linters aggregator
  149. golangci-lint run
  150. golangci-lint linters # list supported linters
  151. golangci-lint run --enable-all # run all linters
  152. # profile (Ref: github.com/alexei-led/presentations)
  153. # collect profile results: cpu, memory, block, mutex
  154. go test -bench="^Benchmark(.*)$" -cpuprofile=/tmp/cpuprofile.out .
  155. # inspect profile results
  156. go tool pprof -http=:8080 /tmp/cpuprofile.out
  157. # goimports install
  158. Install goimports with the following command:
  159. go install golang.org/x/tools/cmd/goimports@latest
  160. And run it with:
  161. goimports -w filename.go
  162. Reference: https://pkg.go.dev/golang.org/x/tools/cmd/goimports
  163. # linting program in golang
  164. Install golint with the following command:
  165. go install golang.org/x/lint/golint@latest
  166. And run it with:
  167. golint filename.go
  168. golint ./... // runs golint over your entire project
  169. # language tools
  170. go build builds Go binaries using only information in the source files
  171. go test unit testing and microbenchmarks
  172. go fmt preprint the code
  173. go get retrieve and install remote packages
  174. go vet static analyzer looking for potential errors in code
  175. go run build and executing code (doesn't generate a binary executable)
  176. go doc display documentation or serving it via HTTP
  177. go rename rename variables, functions, and so on in a type-safe way
  178. go generate standard way to invoke code generators
  179. Go is a statically typed programming language.
  180. # Data types:
  181. string
  182. bool
  183. int
  184. int int8 int16 int32 int64
  185. uint uint8 unit16 unit32 unint64 unintptr
  186. byte - alias for uint8
  187. rune - alias for int32
  188. float32 (single precision) float64 (double precision)
  189. complex64 complex128
  190. int - signed integer
  191. uint - unsigned integer (contain positive numbers or zero)
  192. bytes are an extremely common unit of measurement used on computers
  193. (1 byte = 8 bits, 1024 bytes = 1 kilobyte, 1024 kilobytes = 1 megabyte, etc.)
  194. there are also three machine dependent integer types: uint, int, and uintptr
  195. they are machine dependent because their size depends on the type of architecture
  196. * floating-point numbers are inexact.
  197. (Occasionally it is not possible to represent anumber.)
  198. * like integers, floating-point numbers have a certain size (32 bit or 64 bit)
  199. * using a larger-sized floating-point number increases its precision
  200. * in addition to numbers, there are several other values that can be represented:
  201. "not a number" (NaN, for things like 0/0) and positive and negative infinity
  202. * generally, we should stick with float64 when working with floating-point numbers
  203. * a string is a sequence of characters with a definite length used to represent text
  204. * go strings are made up of individual bytes, usually one for each character
  205. * string literals can be created using double quotes "Mathematical Sciences" or
  206. backticks `Mathematical Sciences`
  207. * the difference between these is that double-quoted strings cannot contain newlines
  208. and they allow special escape sequences.
  209. * for example, \n gets replaced with a newline & \t gets replaced with a tab character
  210. * a boolean value is a special 1-bit integer type used to represent true and false
  211. * three logical operators are used with boolean values: && and, || or, ! not
  212. Constants: true false iota nil
  213. Types: int int8 int16 int32 int64
  214. uint unit8 uint16 uint32 uint64 uintptr
  215. float32 float64 complex128 complex64
  216. bool byte rune string error
  217. Functions: make len cap new append copy close delete complex real imag
  218. panic recover
  219. Keywords: [Reference: https://go.dev/ref/spec]
  220. The following keywords are reserved and may not be used as identifiers.
  221. break default func interface select
  222. case defer go map struct
  223. chan else goto package switch
  224. const fallthrough if range type
  225. continue for import return var
  226. # package main - package declaration (every Go program must start with it. Packages are
  227. Go's way of organizing and reusing code)
  228. Go supports two different styles of comments: // comments in which all the text between
  229. the // and the end of the line is part of the comment, and /*........ */ comments where
  230. everything between the asterisks is part of the comment (may include multiple lines)
  231. # format string
  232. int: %d
  233. float: %f, %.3f
  234. bool: %t
  235. # go documentation example
  236. go doc fmt Println
  237. # fyne (https://developer.fyne.io/started/)
  238. Debian: sudo apt-get install golang gcc libgl1-mesa-dev xorg-dev
  239. # gonum
  240. go install gonum.org/v1/gonum/...@latest
  241. # A half-hour to learn Golang
  242. var declares a variable of a given type:
  243. var x int // Declare x of type int
  244. x = 42 // Assign 42 to x
  245. This can also be written as a single line:
  246. var x int = 42
  247. You can also specify the variable's type implicitly:
  248. var x = 42 // Type int is inferred from 42
  249. This can also be written using a short form:
  250. x := 42
  251. You can declare many variables at the same time:
  252. var a, b, c int
  253. a, b, c = 1, 2, 3
  254. x, y := 40, 80
  255. All declared variables are always initialized to the zero value. If you declare
  256. a variable and use it right away, you can be sure itll have the zero value of
  257. that type.
  258. var x int
  259. foo(x) // Same as foo(0)
  260. The underscore _ is a special identifier. It's used to indicate "no identifier"
  261. and can be used to discard something, or mark it as "used":
  262. // This does nothing because 42 is a constant
  263. _ = 42
  264. // This calls fetchThing but discards its result
  265. _ = fetchThing()
  266. You can import a package for side-effects only by using _ :
  267. import _ "image/png"
  268. A variable with the same name can be re-declared as long as it's in a different
  269. block. That causes it tot shadow an existing variable:
  270. x := 13
  271. if true {
  272. x := x + 3
  273. // Using x after that line only refers to the second x,
  274. // the first x is no longer accessible in this scope.
  275. }
  276. Go does not have a concept of "tuples" like Rust, but it has struct types and
  277. functions can return multiple result values.
  278. Semicolons can be used to mark the end of a statement. But they are optional and
  279. automatically inserted at the end of aline, so they're only needed if you're
  280. placing multiple statements in one line:
  281. var x = 3; var y = 5; var z = y + x
  282. All Go code is formatted with gofmt, the standard Go code formatting tool. It
  283. pretty prints Go code so each statement is on a single line, without semicolons:
  284. var x = 3
  285. var y = 5
  286. var z = y + x
  287. It aligns fields and makes Go code look consistent, no matter who wrote it:
  288. header := component.Header{
  289. CurrentUser: authenticatedUser,
  290. NotificationCount: nc,
  291. ReturnURL: returnURL,
  292. }
  293. Statements can span multiple lines:
  294. notifications := initNotifications(
  295. http.DefaultServeMax,
  296. webdav.Dir(filepath.Join(storedir, "notifications")),
  297. gerritActivity,
  298. users,
  299. githubRouter,
  300. )
  301. func declares a function.
  302. Here's a simple function:
  303. func Greet() {
  304. fmt.Println("Hi there!")
  305. }
  306. Here's a function that returns a 32-bit signed integer:
  307. func FairDiceRoll() int32 {
  308. return 4
  309. }
  310. A pair of brackets declare a block, which has its own scope:
  311. func main() {
  312. x := "out"
  313. {
  314. // This is a different x.
  315. x := "in"
  316. fmt.Println(x)
  317. }
  318. fmt.Println(x)
  319. }
  320. Dots are typically used to access fields of a struct:
  321. var x = struct{ a, b int }{10, 20}
  322. x.a // This is 10.
  323. dmitshur := fetchSomeStruct()
  324. dmitshur.WebsiteURL // This is "https://dmitri.shuralyov.com".
  325. Or call a method on a value:
  326. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  327. Dots are also used to access exported identifiers from other Go packages that
  328. are imported:
  329. import "fmt"
  330. func main() {
  331. fmt.Println("Println is a function in the fmt package")
  332. }
  333. Dots work for accessing struct fields regardless whether they're a value or a
  334. pointer, which makes refactoring code result in a smaller diff.
  335. Named types are declared with the type keyword.
  336. type MyInt int
  337. Struct types are defined with the struct keyword.
  338. type Vec2 struct {
  339. X float64
  340. Y float64
  341. }
  342. They can be initialized using struct literals:
  343. var v1 = Vec2{X: 1.0, Y: 3.0}
  344. var v2 = Vec2{Y: 2.0, X: 4.0 /* The order does not matter, only the names do. */}
  345. One value can be assigned to another:
  346. var v3 = v2
  347. v3.X = 14
  348. You can declare methods on named structs that you defined:
  349. type Number struct {
  350. Odd bool
  351. Value int32
  352. }
  353. // IsStrictlyPositive reports whether Number n is strictly positive.
  354. func (n Number) IsStrictlyPositive() bool {
  355. return n.Value > 0
  356. }
  357. And use them like usual:
  358. func main() {
  359. minusTwo := Number {
  360. Odd: false,
  361. Value: -2,
  362. }
  363. fmt.Println("positive?", minusTwo.IsStrictlyPositive())
  364. // Output:
  365. // positive? false
  366. }
  367. Values are mutable.
  368. n := Number {
  369. Odd: true,
  370. Value: 17,
  371. }
  372. n.Odd = false // This modifies n.
  373. Functions cannot be generic. They can accept parameters that have interface
  374. types. All values implement the blank interface interface{}, so that's a way to
  375. pass a parameter of arbitrary type.
  376. func Println(arg interface{}) {
  377. // Do something with arg.
  378. }
  379. An interface can have 0 or more methods in its method set. When you have a value
  380. of type interface, you can call any of the methods in the method set of said
  381. interface.
  382. type Stringer interface {
  383. String() string
  384. }
  385. func Priintln(s Stringer) {
  386. s.String() // s has a String method, you can call it.
  387. }
  388. Structs cannot be generic either.
  389. Go has slices. They're a reference to multiple contiguous elements in an
  390. underlying array.
  391. v := []int{1, 2, 3, 4, 5}
  392. v2 := v[2:4]
  393. fmt.Printf("v2 = %v\n", v2)
  394. // Output:
  395. // v2 = [3, 4]
  396. The v[2:4] syntax is a slice operation. It makes a new slice that references the
  397. same underlying array as the v slice, but includes elements starting with index
  398. 2 and ending with index 4.
  399. Functions that can fail typically return two result values, the last being of
  400. type error:
  401. u1, err := url.Parse("https://example.com/")
  402. fmt.Println(u1.Host, err)
  403. // Prints "example.com <nil>".
  404. u2, err := url.Parse(":")
  405. fmt.Println(u2, err)
  406. // Prints "<nil> parse ":": missing protocol scheme".
  407. If you want to panic in case of a non-nil error, you can use panic:
  408. u, err := url.Parse(someURL)
  409. if err != nil {
  410. panic(err)
  411. }
  412. fmt.Println(u.Host)
  413. Or write any custom code to handle the non-nil error:
  414. u, err := url.Parse(someURL)
  415. if err != nil {
  416. // Custom behavior to handle the parsing error...
  417. }
  418. fmt.Println(u.Host)
  419. Or you can return the error to the caller, so it can deal with the failure
  420. appropriately:
  421. u, err := url.Parse(someURL)
  422. if err != nil {
  423. return nil, err
  424. }
  425. return u.Host, nil
  426. Or annotate the error with relevant context:
  427. u, err := url.Parse(someURL)
  428. if err != nil {
  429. return nil, fmt.Errorf("failed to parse URL %q, so cannot determine its
  430. host: %v", someURL, err)
  431. }
  432. return u.Host, nil
  433. The * operator can be used to dereference pointers, but it's done implicitly by
  434. Go when accessing fields or calling methods:
  435. type Point struct {
  436. X, Y float64
  437. }
  438. func main() {
  439. p := Point(1, 3)
  440. pp := &p
  441. fmt.Println(pp.X, pp.Y)
  442. // Output: 1 3
  443. }
  444. A function literal represents an anonymous function, It can be assigned to a
  445. variable of function type.
  446. var f func(string) = func(planet string) {
  447. fmt.Println("Hello", planet)
  448. }
  449. Function literals are closures; they may refer to variables defined in a
  450. surrounding function. variables with function type can be passed around and
  451. executed.
  452. func main() {
  453. greeting := "Hello"
  454. greet := func(planet string) {
  455. fmt.Println(greeting, planet) // Variable greeting is captured.
  456. }
  457. forEachPlanet(greet)
  458. // Output:
  459. // Hello Earth
  460. // Hello Mars
  461. // Hello Jupiter
  462. }
  463. // forEachPlanet calls f for each planet.
  464. func forEachPlanet(f func(string)) {
  465. f("Earth")
  466. f("Mars")
  467. f("Jupiter")
  468. }
  469. Anything that can be iterated over can be used in a for loop.
  470. for i := 0; i < 3; i++ {
  471. fmt.Println("index", i)
  472. }
  473. // Output:
  474. // index 0
  475. // index 1
  476. // index 2
  477. There is also a for range loop.
  478. s := []int{52, 49, 21}
  479. for i, v := range s {
  480. fmt.Printf("index=%v value=%v\n", i, v)
  481. }
  482. // Output:
  483. // index=0 value=52
  484. // index=1 value=49
  485. // index=2 value=21
  486. # built-in operators
  487. Operation Result Description
  488. --------------------------------------------------------------------------------------
  489. 0011 & 0101 0001 Bitwise AND
  490. 0011 | 0101 0111 Bitwise OR
  491. 0011 ^ 0101 0110 Bitwise XOR
  492. ^0101 1010 Bitwise NOT (same as 1111 ^ 0101)
  493. 0011 &^ 0101 0010 Bitclear (AND NOT)
  494. 00110101 << 2 11010100 Left shift
  495. 00110101 << 100 00000000 No upper limit on shift count
  496. 00110101 >> 2 00001101 Right shift
  497. # package math/bits
  498. Operation Result Description
  499. ---------------------------------------------------------------------------------------
  500. bits.UintSize 32 or 64 Size of a uint in bits
  501. bits.OnesCount8(00101110) 4 Number of one bits (population count)
  502. bits.Len8(00101110) 6 Bits required to represent number
  503. bits.Len8(00000000) 0
  504. bits.LeadingZeros8(00101110) 2 Number of leading zero bits
  505. bits.LeadingZeros8(00000000) 8
  506. bits.TrailingZeros8(00101110) 1 Number of trailing zero bits
  507. bits.TrailingZeros8(00000000) 8
  508. bits.RotateLeft8(00101110, 3) 01110001 The value rotated left by 3 bits
  509. bits.RotateLeft8(00101110, -3) 11000101 The value rotated right by 3 bits
  510. bits.Reverse8(00101110) 01110100 Bits in reversed order
  511. bits.ReverseBytes16(0x00ff) 0xff00 Bytes in reversed order
  512. Reference: https://yourbasic.org/golang/bitwise-operator-cheat-sheet/