golangref.txt 20 KB

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