├── .github └── workflows │ ├── check.yml │ └── sync.yml ├── .gitignore ├── README.md ├── bin └── gophersnippets ├── docs ├── CNAME ├── css │ ├── highlight.css │ └── spectre.min.css ├── how-to-calculate-the-hamming-distance-between-two-strings.html ├── how-to-calculate-the-sum-of-multiple-numbers.html ├── how-to-check-if-a-slice-contains-a-specific-element.html ├── how-to-check-if-a-string-ends-with-a-substring.html ├── how-to-check-if-a-string-is-lowercase.html ├── how-to-check-if-a-string-is-uppercase.html ├── how-to-check-if-a-string-starts-with-substring.html ├── how-to-check-if-a-type-satisfies-an-interface-at-runtime.html ├── how-to-check-if-string-is-valid-json.html ├── how-to-check-that-a-time-value-is-a-specific-day-of-the-week.html ├── how-to-concatenate-strings.html ├── how-to-convert-int-to-string.html ├── how-to-copy-a-map.html ├── how-to-count-the-number-of-words-in-a-string.html ├── how-to-create-a-set-using-a-map.html ├── how-to-create-multiple-loggers.html ├── how-to-define-a-custom-string-representation-for-a-type.html ├── how-to-define-a-custom-string-representation-of-a-type.html ├── how-to-delete-an-element-from-a-slice.html ├── how-to-disable-log-output.html ├── how-to-filter-a-slice.html ├── how-to-find-the-maximum-element-of-a-slice.html ├── how-to-find-the-minimum-element-of-a-slice.html ├── how-to-format-go-code-programmatically.html ├── how-to-get-the-md5-checksum-of-a-string.html ├── how-to-get-the-sha1-checksum-of-a-string.html ├── how-to-get-the-sha256-checksum-of-a-string.html ├── how-to-include-the-filename-and-the-line-number-in-a-logger-output.html ├── how-to-measure-the-execution-time-of-a-function.html ├── how-to-parse-comments-from-go-code.html ├── how-to-pretty-print-json.html ├── how-to-print-a-raw-http-response.html ├── how-to-print-go-version.html ├── how-to-print-information-about-the-operating-system-architecture-and-pointer-size.html ├── how-to-print-the-binary-representation-of-an-integer.html ├── how-to-print-the-same-variable-multiple-times-using-printf.html ├── how-to-read-an-http-response-status-code.html ├── how-to-remove-duplicate-elements-from-a-slice.html ├── how-to-reverse-a-slice.html ├── how-to-reverse-a-string.html ├── how-to-shuffle-a-slice.html ├── how-to-split-a-slice-in-chunks.html ├── how-to-test-a-function-that-panics.html ├── index.html └── what-is-the-maximum-value-of-numeric-types.html ├── snippets ├── how-to-calculate-the-hamming-distance-between-two-strings │ ├── main_test.go │ └── metadata.yml ├── how-to-calculate-the-sum-of-multiple-numbers │ ├── main_test.go │ └── metadata.yml ├── how-to-check-if-a-slice-contains-a-specific-element │ ├── main_test.go │ └── metadata.yml ├── how-to-check-if-a-string-ends-with-a-substring │ ├── main_test.go │ └── metadata.yml ├── how-to-check-if-a-string-is-lowercase │ ├── main_test.go │ └── metadata.yml ├── how-to-check-if-a-string-is-uppercase │ ├── main_test.go │ └── metadata.yml ├── how-to-check-if-a-string-starts-with-substring │ ├── main_test.go │ └── metadata.yml ├── how-to-check-if-a-type-satisfies-an-interface-at-runtime │ ├── main_test.go │ └── metadata.yml ├── how-to-check-if-string-is-valid-json │ ├── main_test.go │ └── metadata.yml ├── how-to-check-that-a-time-value-is-a-specific-day-of-the-week │ ├── main_test.go │ └── metadata.yml ├── how-to-concatenate-strings │ ├── main_test.go │ └── metadata.yml ├── how-to-convert-int-to-string │ ├── main_test.go │ └── metadata.yml ├── how-to-copy-a-map │ ├── main_test.go │ └── metadata.yml ├── how-to-count-the-number-of-words-in-a-string │ ├── main_test.go │ └── metadata.yml ├── how-to-create-a-set-using-a-map │ ├── main_test.go │ └── metadata.yml ├── how-to-create-multiple-loggers │ ├── main_test.go │ └── metadata.yml ├── how-to-define-a-custom-string-representation-for-a-type │ ├── main_test.go │ └── metadata.yml ├── how-to-delete-an-element-from-a-slice │ ├── main_test.go │ └── metadata.yml ├── how-to-disable-log-output │ ├── main_test.go │ └── metadata.yml ├── how-to-filter-a-slice │ ├── main_test.go │ └── metadata.yml ├── how-to-find-the-maximum-element-of-a-slice │ ├── main_test.go │ └── metadata.yml ├── how-to-find-the-minimum-element-of-a-slice │ ├── main_test.go │ └── metadata.yml ├── how-to-format-go-code-programmatically │ ├── main_test.go │ └── metadata.yml ├── how-to-get-the-md5-checksum-of-a-string │ ├── main_test.go │ └── metadata.yml ├── how-to-get-the-sha1-checksum-of-a-string │ ├── main_test.go │ └── metadata.yml ├── how-to-get-the-sha256-checksum-of-a-string │ ├── main_test.go │ └── metadata.yml ├── how-to-include-the-filename-and-the-line-number-in-a-logger-output │ ├── main_test.go │ └── metadata.yml ├── how-to-measure-the-execution-time-of-a-function │ ├── main_test.go │ └── metadata.yml ├── how-to-parse-comments-from-go-code │ ├── main_test.go │ └── metadata.yml ├── how-to-pretty-print-json │ ├── main_test.go │ └── metadata.yml ├── how-to-print-a-raw-http-response │ ├── main_test.go │ └── metadata.yml ├── how-to-print-go-version │ ├── main_test.go │ └── metadata.yml ├── how-to-print-information-about-the-operating-system-architecture-and-pointer-size │ ├── main_test.go │ └── metadata.yml ├── how-to-print-the-binary-representation-of-an-integer │ ├── main_test.go │ └── metadata.yml ├── how-to-print-the-same-variable-multiple-times-using-printf │ ├── main_test.go │ └── metadata.yml ├── how-to-read-an-http-response-status-code │ ├── main_test.go │ └── metadata.yml ├── how-to-remove-duplicate-elements-from-a-slice │ ├── main_test.go │ └── metadata.yml ├── how-to-reverse-a-slice │ ├── main_test.go │ └── metadata.yml ├── how-to-reverse-a-string │ ├── main_test.go │ └── metadata.yml ├── how-to-shuffle-a-slice │ ├── main_test.go │ └── metadata.yml ├── how-to-split-a-slice-in-chunks │ ├── main_test.go │ └── metadata.yml ├── how-to-test-a-function-that-panics │ ├── main_test.go │ └── metadata.yml └── what-is-the-maximum-value-of-numeric-types │ ├── main_test.go │ └── metadata.yml └── tools └── templates ├── html_index.html ├── html_page.html ├── issue.tmpl └── readme.md /.github/workflows/check.yml: -------------------------------------------------------------------------------- 1 | name: check-pr 2 | on: 3 | pull_request: 4 | branches: 5 | - master 6 | jobs: 7 | check-pr: 8 | name: check-pr 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | - uses: actions/setup-go@v1 13 | with: 14 | go-version: 1.14.2 15 | - name: go vet 16 | run: | 17 | cd snippets 18 | go vet ./... 19 | - name: code compiles on playground, includes tests and has the correct format 20 | run: | 21 | ./bin/gophersnippets -pr-check -playground -playground-ua="gophersnippets.com/v1" 22 | -------------------------------------------------------------------------------- /.github/workflows/sync.yml: -------------------------------------------------------------------------------- 1 | name: sync-issues-with-content 2 | on: 3 | push: 4 | branches: 5 | - master 6 | jobs: 7 | sync-content-issues: 8 | name: sync-issues-with-content 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | with: 13 | persist-credentials: false 14 | - name: generate html content 15 | run: | 16 | GITHUBTOKEN=${{ secrets.GITHUBTOKEN }} GITHUB_REPOSITORY=${{ github.repository }} ./bin/gophersnippets -github-issues -playground -playground-ua="gophersnippets.com/v1" 17 | git config --global user.email "${{ secrets.GIT_EMAIL }}" 18 | git config --global user.name "${{ secrets.GIT_NAME }}" 19 | git add . 20 | git diff --staged --quiet || git commit -m "generate html content" 21 | - name: Push changes 22 | uses: ad-m/github-push-action@master 23 | with: 24 | github_token: ${{ secrets.GITHUBTOKEN }} 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea -------------------------------------------------------------------------------- /bin/gophersnippets: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/psampaz/gophersnippets/ca75d4a5c068ee21e8c5b37b1e9d6c4ba60fb16d/bin/gophersnippets -------------------------------------------------------------------------------- /docs/CNAME: -------------------------------------------------------------------------------- 1 | gophersnippets.com -------------------------------------------------------------------------------- /docs/css/highlight.css: -------------------------------------------------------------------------------- 1 | /* Background */ .chroma { background-color: #f9f9f9 } 2 | /* Error */ .chroma .err { } 3 | /* LineTableTD */ .chroma .lntd { vertical-align: top; padding: 0; margin: 0; border: 0; } 4 | /* LineTable */ .chroma .lntable { border-spacing: 0; padding: 0; margin: 0; border: 0; width: auto; overflow: auto; display: block; } 5 | /* LineHighlight */ .chroma .hl { display: block; width: 100%;background-color: #e5e5e5 } 6 | /* LineNumbersTable */ .chroma .lnt { margin-right: 0.4em; padding: 0 0.4em 0 0.4em;color: #7f7f7f } 7 | /* LineNumbers */ .chroma .ln { margin-right: 0.4em; padding: 0 0.4em 0 0.4em;color: #7f7f7f } 8 | /* Keyword */ .chroma .k { color: #008000; font-weight: bold } 9 | /* KeywordConstant */ .chroma .kc { color: #008000; font-weight: bold } 10 | /* KeywordDeclaration */ .chroma .kd { color: #008000; font-weight: bold } 11 | /* KeywordNamespace */ .chroma .kn { color: #008000; font-weight: bold } 12 | /* KeywordPseudo */ .chroma .kp { color: #008000 } 13 | /* KeywordReserved */ .chroma .kr { color: #008000; font-weight: bold } 14 | /* KeywordType */ .chroma .kt { color: #b00040 } 15 | /* NameAttribute */ .chroma .na { color: #7d9029 } 16 | /* NameBuiltin */ .chroma .nb { color: #008000 } 17 | /* NameClass */ .chroma .nc { color: #0000ff; font-weight: bold } 18 | /* NameConstant */ .chroma .no { color: #880000 } 19 | /* NameDecorator */ .chroma .nd { color: #aa22ff } 20 | /* NameEntity */ .chroma .ni { color: #999999; font-weight: bold } 21 | /* NameException */ .chroma .ne { color: #d2413a; font-weight: bold } 22 | /* NameFunction */ .chroma .nf { color: #0000ff } 23 | /* NameLabel */ .chroma .nl { color: #a0a000 } 24 | /* NameNamespace */ .chroma .nn { color: #0000ff; font-weight: bold } 25 | /* NameTag */ .chroma .nt { color: #008000; font-weight: bold } 26 | /* NameVariable */ .chroma .nv { color: #19177c } 27 | /* LiteralString */ .chroma .s { color: #ba2121 } 28 | /* LiteralStringAffix */ .chroma .sa { color: #ba2121 } 29 | /* LiteralStringBacktick */ .chroma .sb { color: #ba2121 } 30 | /* LiteralStringChar */ .chroma .sc { color: #ba2121 } 31 | /* LiteralStringDelimiter */ .chroma .dl { color: #ba2121 } 32 | /* LiteralStringDoc */ .chroma .sd { color: #ba2121; font-style: italic } 33 | /* LiteralStringDouble */ .chroma .s2 { color: #ba2121 } 34 | /* LiteralStringEscape */ .chroma .se { color: #bb6622; font-weight: bold } 35 | /* LiteralStringHeredoc */ .chroma .sh { color: #ba2121 } 36 | /* LiteralStringInterpol */ .chroma .si { color: #bb6688; font-weight: bold } 37 | /* LiteralStringOther */ .chroma .sx { color: #008000 } 38 | /* LiteralStringRegex */ .chroma .sr { color: #bb6688 } 39 | /* LiteralStringSingle */ .chroma .s1 { color: #ba2121 } 40 | /* LiteralStringSymbol */ .chroma .ss { color: #19177c } 41 | /* LiteralNumber */ .chroma .m { color: #666666 } 42 | /* LiteralNumberBin */ .chroma .mb { color: #666666 } 43 | /* LiteralNumberFloat */ .chroma .mf { color: #666666 } 44 | /* LiteralNumberHex */ .chroma .mh { color: #666666 } 45 | /* LiteralNumberInteger */ .chroma .mi { color: #666666 } 46 | /* LiteralNumberIntegerLong */ .chroma .il { color: #666666 } 47 | /* LiteralNumberOct */ .chroma .mo { color: #666666 } 48 | /* Operator */ .chroma .o { color: #666666 } 49 | /* OperatorWord */ .chroma .ow { color: #aa22ff; font-weight: bold } 50 | /* Comment */ .chroma .c { color: #408080; font-style: italic } 51 | /* CommentHashbang */ .chroma .ch { color: #408080; font-style: italic } 52 | /* CommentMultiline */ .chroma .cm { color: #408080; font-style: italic } 53 | /* CommentSingle */ .chroma .c1 { color: #408080; font-style: italic } 54 | /* CommentSpecial */ .chroma .cs { color: #408080; font-style: italic } 55 | /* CommentPreproc */ .chroma .cp { color: #bc7a00 } 56 | /* CommentPreprocFile */ .chroma .cpf { color: #bc7a00 } 57 | /* GenericDeleted */ .chroma .gd { color: #a00000 } 58 | /* GenericEmph */ .chroma .ge { font-style: italic } 59 | /* GenericError */ .chroma .gr { color: #ff0000 } 60 | /* GenericHeading */ .chroma .gh { color: #000080; font-weight: bold } 61 | /* GenericInserted */ .chroma .gi { color: #00a000 } 62 | /* GenericOutput */ .chroma .go { color: #888888 } 63 | /* GenericPrompt */ .chroma .gp { color: #000080; font-weight: bold } 64 | /* GenericStrong */ .chroma .gs { font-weight: bold } 65 | /* GenericSubheading */ .chroma .gu { color: #800080; font-weight: bold } 66 | /* GenericTraceback */ .chroma .gt { color: #0044dd } 67 | /* GenericUnderline */ .chroma .gl { text-decoration: underline } 68 | /* TextWhitespace */ .chroma .w { color: #bbbbbb } -------------------------------------------------------------------------------- /docs/how-to-check-if-a-string-ends-with-a-substring.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to check if a string ends with a substring - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to check if a string ends with a substring

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"fmt"
25 | 	"strings"
26 | )
27 | 
28 | func Example() {
29 | 	fmt.Println(strings.HasSuffix("abcdefg", "fg"))
30 | 	fmt.Println(strings.HasSuffix("abcdefg", "Fg"))
31 | 	// Output:
32 | 	// true
33 | 	// false
34 | }
35 | 
36 |

37 |

38 | by psampaz - 39 | source code - comment below or here 41 |

42 | 49 |
50 |
51 |
52 |
53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /docs/how-to-check-if-a-string-starts-with-substring.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to check if a string starts with substring - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to check if a string starts with substring

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"fmt"
25 | 	"strings"
26 | )
27 | 
28 | func Example() {
29 | 	fmt.Println(strings.HasPrefix("abcdefg", "ab"))
30 | 	fmt.Println(strings.HasPrefix("abcdefg", "Ab"))
31 | 	// Output:
32 | 	// true
33 | 	// false
34 | }
35 | 
36 |

37 |

38 | by psampaz - 39 | source code - comment below or here 41 |

42 | 49 |
50 |
51 |
52 |
53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /docs/how-to-check-if-string-is-valid-json.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to check if string is valid JSON - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to check if string is valid JSON

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"encoding/json"
25 | 	"fmt"
26 | )
27 | 
28 | func Example() {
29 | 	valid := `{"foo":"bar"}`
30 | 	invalid := `}{`
31 | 
32 | 	fmt.Println(json.Valid([]byte(valid)))
33 | 	fmt.Println(json.Valid([]byte(invalid)))
34 | 	// Output:
35 | 	// true
36 | 	// false
37 | }
38 | 
39 |

40 |

41 | by psampaz - 42 | source code - comment below or here 44 |

45 | 52 |
53 |
54 |
55 |
56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /docs/how-to-check-that-a-time-value-is-a-specific-day-of-the-week.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to check that a time value is a specific day of the week - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to check that a time value is a specific day of the week

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"fmt"
25 | 	"time"
26 | )
27 | 
28 | func Example() {
29 | 	// The time package offers a time.Weekday() method which returns
30 | 	// a time.Weekday value	https://pkg.go.dev/time?tab=doc#Weekday
31 | 	now := time.Now()
32 | 	if now.Weekday() == time.Tuesday {
33 | 		fmt.Println("The day on Go playground is always Tuesday")
34 | 	}
35 | 	// Output:
36 | 	// The day on Go playground is always Tuesday
37 | }
38 | 
39 |

40 |

41 | by psampaz - 42 | source code - comment below or here 44 |

45 | 52 |
53 |
54 |
55 |
56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /docs/how-to-concatenate-strings.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to concatenate strings - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to concatenate strings

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"fmt"
25 | 	"strings"
26 | )
27 | 
28 | func Example() {
29 | 	// Create a slice of the strings that you want to join together
30 | 	strs := []string{"aa", "bb", "cc"}
31 | 	//Use the strings.Join function to join them, by passing the desired separator
32 | 	fmt.Println(strings.Join(strs, "-"))
33 | 	fmt.Println(strings.Join(strs, ", "))
34 | 	fmt.Println(strings.Join(strs, ""))
35 | 	// Output:
36 | 	// aa-bb-cc
37 | 	// aa, bb, cc
38 | 	// aabbcc
39 | }
40 | 
41 |

42 |

43 | by psampaz - 44 | source code - comment below or here 46 |

47 | 54 |
55 |
56 |
57 |
58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /docs/how-to-convert-int-to-string.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to convert int to string - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to convert int to string

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"fmt"
25 | 	"strconv"
26 | )
27 | 
28 | func Example_itoa() {
29 | 	// Converting an int to a string can be done
30 | 	// using the `strconv.Itoa` (integer to ascii) function
31 | 	a := strconv.Itoa(1234)
32 | 	fmt.Printf("%q\n", a)
33 | 	// Output:
34 | 	// "1234"
35 | }
36 | 
37 | func Example_formatInt() {
38 | 	// `strconv.Itoa` is calls internally
39 | 	// `FormatInt(int64(i), 10)` so another way
40 | 	//  to  convert an int to  a string is the following:
41 | 	b := strconv.FormatInt(int64(1234), 10)
42 | 	fmt.Printf("%q\n", b)
43 | 	// Output:
44 | 	// "1234"
45 | }
46 | 
47 | func Example_sprintf() {
48 | 	// A third way would be to use the `fmt.Sprintf` method:
49 | 	c := fmt.Sprintf("%d", 1234)
50 | 	fmt.Printf("%q\n", c)
51 | 	// Output:
52 | 	// "1234"
53 | }
54 | 
55 |

56 |

57 | by psampaz - 58 | source code - comment below or here 60 |

61 | 68 |
69 |
70 |
71 |
72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /docs/how-to-count-the-number-of-words-in-a-string.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to count the number of words in a string - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to count the number of words in a string

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"fmt"
25 | 	"strings"
26 | )
27 | 
28 | // strings.Fields() splits a string around one or more
29 | // consecutive whitespaces (https://golang.org/pkg/unicode/#IsSpace)
30 | // The number of fields is the actual number of words
31 | func CountWords(s string) int {
32 | 	return len(strings.Fields(s))
33 | }
34 | 
35 | // If the words are not separated by whitespaces
36 | // but with comma (a csv row for example) or whatever else,
37 | // you can use the strings.FieldsFunc() and explicitly define
38 | // the points of split
39 | func CountWordsFunc(s string, f func(rune) bool) int {
40 | 	return len(strings.FieldsFunc(s, f))
41 | }
42 | 
43 | func ExampleCountWords() {
44 | 	wc := CountWords("  How  to count words? \n")
45 | 	fmt.Println(wc)
46 | 	// Output:
47 | 	// 4
48 | }
49 | 
50 | func ExampleCountWordsFunc() {
51 | 	f := func(c rune) bool {
52 | 		return c == ','
53 | 	}
54 | 	wc := CountWordsFunc("word1, word2, word3", f)
55 | 	fmt.Println(wc)
56 | 	// Output:
57 | 	// 3
58 | }
59 | 
60 |

61 |

62 | by psampaz - 63 | source code - comment below or here 65 |

66 | 73 |
74 |
75 |
76 |
77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /docs/how-to-create-a-set-using-a-map.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to create a set using a map - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to create a set using a map

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import "fmt"
24 | 
25 | // A set is a unordered collection of unique data.
26 | // Go does not have a built-in set data structure
27 | // but you can easily create one using a map
28 | func Example() {
29 | 	// The map keys are a unique unordered collection.
30 | 	// So if you just ignore the values, a map can be viewed as a set
31 | 	// The most space optimized way to do this is to use the empty struct
32 | 	// as the map value type, since the empty struct (a struct with no fields)
33 | 	// occupies zero bytes of storage
34 | 	// https://dave.cheney.net/2014/03/25/the-empty-struct
35 | 	set := make(map[string]struct{})
36 | 	fmt.Println(set)
37 | 	// Add new elements in the set
38 | 	set["a"] = struct{}{}
39 | 	set["b"] = struct{}{}
40 | 	set["c"] = struct{}{}
41 | 	fmt.Println(set)
42 | 
43 | 	// Check if an element exists in the set
44 | 	if _, exists := set["a"]; exists {
45 | 		fmt.Println("a exists in the set")
46 | 	}
47 | 	// Delete an element from the set
48 | 	delete(set, "b")
49 | 	fmt.Println(set)
50 | 	// Output:
51 | 	// map[]
52 | 	// map[a:{} b:{} c:{}]
53 | 	// a exists in the set
54 | 	// map[a:{} c:{}]
55 | }
56 | 
57 |

58 |

59 | by psampaz - 60 | source code - comment below or here 62 |

63 | 70 |
71 |
72 |
73 |
74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /docs/how-to-create-multiple-loggers.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to create multiple loggers - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to create multiple loggers

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"log"
25 | 	"os"
26 | )
27 | 
28 | func Example() {
29 | 	// You can create as many loggers you want using the log.New method
30 | 	// Each logger can write logs in different targets, use different prefix
31 | 	// and different settings
32 | 	logger1 := log.New(os.Stdout, "logger1: ", log.LstdFlags)
33 | 	logger2 := log.New(os.Stdout, "logger2: ", log.LstdFlags|log.Lmicroseconds)
34 | 	logger1.Println("Message from logger1")
35 | 	logger2.Println("Message from logger2")
36 | 	// Output:
37 | 	// logger1: 2009/11/10 23:00:00 Message from logger1
38 | 	// logger2: 2009/11/10 23:00:00.000000 Message from logger2
39 | }
40 | 
41 |

42 |

43 | by psampaz - 44 | source code - comment below or here 46 |

47 | 54 |
55 |
56 |
57 |
58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /docs/how-to-define-a-custom-string-representation-of-a-type.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to define a custom string representation of a type - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to define a custom string representation of a type

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
 22 | 
 23 | import "fmt"
 24 | 
 25 | // UserA does not implement the Stringer interface
 26 | type UserA struct {
 27 | 	FirstName string
 28 | 	LastName  string
 29 | }
 30 | 
 31 | // UserB implements the Stringer interface
 32 | type UserB struct {
 33 | 	FirstName string
 34 | 	LastName  string
 35 | }
 36 | 
 37 | func (u UserB) String() string {
 38 | 	return fmt.Sprintf("First name is %s, last name is %s", u.FirstName, u.LastName)
 39 | }
 40 | 
 41 | // BoolA does implements the Stringer interface
 42 | type BoolA bool
 43 | 
 44 | // BoolB implements the Stringer interface
 45 | type BoolB bool
 46 | 
 47 | func (b BoolB) String() string {
 48 | 	if b {
 49 | 		return "Yes"
 50 | 	} else {
 51 | 		return "No"
 52 | 	}
 53 | }
 54 | 
 55 | // To control the string representation of a type
 56 | // the type needs to implement the Stringer interface
 57 | // https://pkg.go.dev/fmt?tab=doc#Stringer
 58 | // type Stringer interface {
 59 | //	String() string
 60 | // }
 61 | // The String method is used to print values passed as an operand
 62 | // to any format that accepts a string or to an unformatted printer
 63 | // such as Print.
 64 | func Example() {
 65 | 	a := UserA{"John", "Doe"}
 66 | 	b := UserB{"John", "Doe"}
 67 | 	c := BoolA(true)
 68 | 	d := BoolB(true)
 69 | 
 70 | 	fmt.Println(a)
 71 | 	fmt.Println(b)
 72 | 	fmt.Println(c)
 73 | 	fmt.Println(d)
 74 | 	// Output:
 75 | 	// {John Doe}
 76 | 	// First name is John, last name is Doe
 77 | 	// true
 78 | 	// Yes
 79 | }
 80 | 
81 |

82 |

83 | by psampaz - 84 | source code - comment below or here 86 |

87 | 94 |
95 |
96 |
97 |
98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /docs/how-to-disable-log-output.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to disable log output - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to disable log output

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"io/ioutil"
25 | 	"log"
26 | )
27 | 
28 | func Example() {
29 | 	// If you want to disable log output (during test for example)
30 | 	// you have to set the logger ouput to ioutil.Discard
31 | 	// which is an io.Writer on which all Write calls succeed
32 | 	// without doing anything
33 | 	log.SetOutput(ioutil.Discard)
34 | 	log.Println("log disabled")
35 | 	// Output:
36 | 	//
37 | }
38 | 
39 |

40 |

41 | by psampaz - 42 | source code - comment below or here 44 |

45 | 52 |
53 |
54 |
55 |
56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /docs/how-to-format-go-code-programmatically.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to format Go code programmatically - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to format Go code programmatically

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

// Code can be formatted programmatically in the same way like running go fmt,
22 | // using the go/format package
23 | package main
24 | 
25 | import (
26 | 	"fmt"
27 | 	"go/format"
28 | 	"log"
29 | )
30 | 
31 | func Example() {
32 | 	unformatted := `
33 | package main
34 |        import "fmt"
35 | 
36 | func  main(   )  {
37 |     x :=    12
38 | fmt.Printf(   "%d",   x  )
39 | 	}
40 | 
41 | 
42 | `
43 | 	formatted, err := format.Source([]byte(unformatted))
44 | 	if err != nil {
45 | 		log.Fatal(err)
46 | 	}
47 | 	fmt.Printf("%s", string(formatted))
48 | 	// Output:
49 | 	// package main
50 | 	//
51 | 	// import "fmt"
52 | 	//
53 | 	// func main() {
54 | 	//	x := 12
55 | 	//	fmt.Printf("%d", x)
56 | 	// }
57 | }
58 | 
59 |

60 |

61 | by psampaz - 62 | source code - comment below or here 64 |

65 | 72 |
73 |
74 |
75 |
76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /docs/how-to-get-the-md5-checksum-of-a-string.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to get the md5 checksum of a string - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to get the md5 checksum of a string

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"crypto/md5"
25 | 	"fmt"
26 | 	"testing"
27 | )
28 | 
29 | func md5Checksum(s string) string {
30 | 	return fmt.Sprintf("%x", md5.Sum([]byte(s)))
31 | }
32 | 
33 | func Test_md5Checksum(t *testing.T) {
34 | 	tests := []struct {
35 | 		name string
36 | 		s    string
37 | 		want string
38 | 	}{
39 | 		{
40 | 			name: "empty string",
41 | 			s:    "",
42 | 			want: "d41d8cd98f00b204e9800998ecf8427e",
43 | 		},
44 | 		{
45 | 			name: "hello world",
46 | 			s:    "hello world",
47 | 			want: "5eb63bbbe01eeed093cb22bb8f5acdc3",
48 | 		},
49 | 	}
50 | 	for _, tt := range tests {
51 | 		t.Run(tt.name, func(t *testing.T) {
52 | 			if got := md5Checksum(tt.s); got != tt.want {
53 | 				t.Errorf("md5Checksum(%q) = %v, want %v", tt.s, got, tt.want)
54 | 			}
55 | 		})
56 | 	}
57 | }
58 | 
59 |

60 |

61 | by psampaz - 62 | source code - comment below or here 64 |

65 | 72 |
73 |
74 |
75 |
76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /docs/how-to-get-the-sha1-checksum-of-a-string.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to get the sha1 checksum of a string - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to get the sha1 checksum of a string

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"crypto/sha1"
25 | 	"fmt"
26 | 	"testing"
27 | )
28 | 
29 | func Sha1Checksum(s string) string {
30 | 	return fmt.Sprintf("%x", sha1.Sum([]byte(s)))
31 | }
32 | 
33 | func Test_Sha1Checksum(t *testing.T) {
34 | 	tests := []struct {
35 | 		name string
36 | 		s    string
37 | 		want string
38 | 	}{
39 | 		{
40 | 			name: "empty string",
41 | 			s:    "",
42 | 			want: "da39a3ee5e6b4b0d3255bfef95601890afd80709",
43 | 		},
44 | 		{
45 | 			name: "hello world",
46 | 			s:    "hello world",
47 | 			want: "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed",
48 | 		},
49 | 	}
50 | 	for _, tt := range tests {
51 | 		t.Run(tt.name, func(t *testing.T) {
52 | 			if got := Sha1Checksum(tt.s); got != tt.want {
53 | 				t.Errorf("Sha1Checksum(%q) = %v, want %v", tt.s, got, tt.want)
54 | 			}
55 | 		})
56 | 	}
57 | }
58 | 
59 |

60 |

61 | by psampaz - 62 | source code - comment below or here 64 |

65 | 72 |
73 |
74 |
75 |
76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /docs/how-to-get-the-sha256-checksum-of-a-string.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to get the sha256 checksum of a string - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to get the sha256 checksum of a string

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"crypto/sha256"
25 | 	"fmt"
26 | 	"testing"
27 | )
28 | 
29 | func Sha256Checksum(s string) string {
30 | 	return fmt.Sprintf("%x", sha256.Sum256([]byte(s)))
31 | }
32 | 
33 | func Test_Sha256Checksum(t *testing.T) {
34 | 	tests := []struct {
35 | 		name string
36 | 		s    string
37 | 		want string
38 | 	}{
39 | 		{
40 | 			name: "empty string",
41 | 			s:    "",
42 | 			want: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
43 | 		},
44 | 		{
45 | 			name: "hello world",
46 | 			s:    "hello world",
47 | 			want: "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9",
48 | 		},
49 | 	}
50 | 	for _, tt := range tests {
51 | 		t.Run(tt.name, func(t *testing.T) {
52 | 			if got := Sha256Checksum(tt.s); got != tt.want {
53 | 				t.Errorf("Sha256Checksum(%q) = %v, want %v", tt.s, got, tt.want)
54 | 			}
55 | 		})
56 | 	}
57 | }
58 | 
59 |

60 |

61 | by psampaz - 62 | source code - comment below or here 64 |

65 | 72 |
73 |
74 |
75 |
76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /docs/how-to-include-the-filename-and-the-line-number-in-a-logger-output.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to include the filename and the line number in a logger output - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to include the filename and the line number in a logger output

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"log"
25 | 	"os"
26 | )
27 | 
28 | func Example() {
29 | 	// You can configure the output format of a logger using
30 | 	// flags https://golang.org/pkg/log/#pkg-constants
31 | 	// Use log.LshortfileIf to print the filename without
32 | 	// the full path and the line number or
33 | 	// Use log.Llongfile to print the filename with
34 | 	// the full path and the line number
35 | 	// The log.Llongfile example is not included below
36 | 	// because playground use different path each time
37 | 	log.SetOutput(os.Stdout)
38 | 	log.SetFlags(log.Lshortfile)
39 | 	log.Println("Hello world")
40 | 	// Output:
41 | 	// prog.go:20: Hello world
42 | }
43 | 
44 |

45 |

46 | by psampaz - 47 | source code - comment below or here 49 |

50 | 57 |
58 |
59 |
60 |
61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /docs/how-to-measure-the-execution-time-of-a-function.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to measure the execution time of a function - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to measure the execution time of a function

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

// This example demonstrates simple execution time calculation
22 | // If you need a detailed report on a function's performance
23 | // you should use Go benchmark functions
24 | // https://golang.org/pkg/testing/#hdr-Benchmarks
25 | // https://dave.cheney.net/2013/06/30/how-to-write-benchmarks-in-go
26 | package main
27 | 
28 | import (
29 | 	"fmt"
30 | 	"time"
31 | )
32 | 
33 | func f() {
34 | 	// first we calculate the exact time the function
35 | 	// started the execution
36 | 	start := time.Now()
37 | 	// Then we calculate the execution time duration
38 | 	// inside a deferred function, since it will be execute after f() returns
39 | 	defer func(start time.Time) {
40 | 		dur := time.Since(start)
41 | 		fmt.Printf("f() took %0.0f to execute", dur.Seconds())
42 | 	}(start)
43 | 	// pause the execution for 2 seconds
44 | 	time.Sleep(2 * time.Second)
45 | }
46 | 
47 | func Example() {
48 | 	f()
49 | 	// Output:
50 | 	// f() took 2 to execute
51 | }
52 | 
53 |

54 |

55 | by psampaz - 56 | source code - comment below or here 58 |

59 | 66 |
67 |
68 |
69 |
70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /docs/how-to-parse-comments-from-go-code.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to parse comments from Go Code - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to parse comments from Go Code

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

// Comments from Go code can be parsed using
22 | // go/parser package
23 | package main
24 | 
25 | import (
26 | 	"fmt"
27 | 	"go/parser"
28 | 	"go/token"
29 | )
30 | 
31 | func Example() {
32 | 	src := `
33 | // Calculator package provides methods 
34 | // for basic int calculation 
35 | package calculator
36 | 
37 | // Import of fmt package 
38 | import "fmt"
39 | 
40 | // Add adds two integers
41 | func Add(a, b int) int {
42 | 	// calculate the result
43 | 	result := a + b
44 | 	// return the result
45 | 	return result
46 | }
47 | `
48 | 	fs := token.NewFileSet()
49 | 	f, err := parser.ParseFile(fs, "", src, parser.ParseComments)
50 | 	if err != nil {
51 | 		fmt.Println(err)
52 | 		return
53 | 	}
54 | 
55 | 	for _, c := range f.Comments {
56 | 		fmt.Println(c.Text())
57 | 	}
58 | 	// Output:
59 | 	// Calculator package provides methods
60 | 	// for basic int calculation
61 | 	//
62 | 	// Import of fmt package
63 | 	//
64 | 	// Add adds two integers
65 | 	//
66 | 	// calculate the result
67 | 	//
68 | 	// return the result
69 | }
70 | 
71 |

72 |

73 | by psampaz - 74 | source code - comment below or here 76 |

77 | 84 |
85 |
86 |
87 |
88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /docs/how-to-pretty-print-json.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to pretty print JSON - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to pretty print JSON

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"encoding/json"
25 | 	"fmt"
26 | )
27 | 
28 | type Student struct {
29 | 	Name    string
30 | 	Age     string
31 | 	Lessons []string
32 | }
33 | 
34 | func Example() {
35 | 	s := Student{
36 | 		Name: "John",
37 | 		Age:  "17",
38 | 		Lessons: []string{
39 | 			"Mathematics",
40 | 			"Computer science",
41 | 			"Philosophy",
42 | 		},
43 | 	}
44 | 
45 | 	// By using json.Marshal the output will be one line json string
46 | 	// which is difficult to read or debug
47 | 	jsonBytes, err := json.Marshal(s)
48 | 	if err != nil {
49 | 		fmt.Println(err)
50 | 	}
51 | 	fmt.Printf("\nUgly print:\n%s\n", jsonBytes)
52 | 
53 | 	// The easiest way to achieve a human readable and pretty print
54 | 	// is to use the json.MarshalIndent
55 | 	jsonBytes, err = json.MarshalIndent(s, "", "\t")
56 | 	if err != nil {
57 | 		fmt.Println(err)
58 | 	}
59 | 	fmt.Printf("\nPretty print:\n%s\n", jsonBytes)
60 | 	// Output:
61 | 	//
62 | 	// Ugly print:
63 | 	// {"Name":"John","Age":"17","Lessons":["Mathematics","Computer science","Philosophy"]}
64 | 	//
65 | 	// Pretty print:
66 | 	// {
67 | 	//	"Name": "John",
68 | 	//	"Age": "17",
69 | 	//	"Lessons": [
70 | 	//		"Mathematics",
71 | 	//		"Computer science",
72 | 	//		"Philosophy"
73 | 	//	]
74 | 	// }
75 | }
76 | 
77 |

78 |

79 | by psampaz - 80 | source code - comment below or here 82 |

83 | 90 |
91 |
92 |
93 |
94 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /docs/how-to-print-a-raw-http-response.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to print a raw HTTP response - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to print a raw HTTP response

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"fmt"
25 | 	"log"
26 | 	"net/http"
27 | 	"net/http/httptest"
28 | 	"net/http/httputil"
29 | )
30 | 
31 | func Example() {
32 | 	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
33 | 		w.Header().Set("Date", "Wed, 01 Jan 2020 00:00:00 GMT")
34 | 		w.WriteHeader(http.StatusOK)
35 | 		w.Write([]byte("hello world"))
36 | 	}))
37 | 	defer ts.Close()
38 | 
39 | 	resp, err := http.Get(ts.URL)
40 | 	if err != nil {
41 | 		fmt.Println(err)
42 | 	}
43 | 	defer resp.Body.Close()
44 | 
45 | 	// DumpResponse returns wire representation
46 | 	// of the http response
47 | 	dump, err := httputil.DumpResponse(resp, true)
48 | 	if err != nil {
49 | 		log.Fatal(err)
50 | 	}
51 | 	// %q is used here to make the testable example work
52 | 	// use %s to print in multiple lines:
53 | 	// HTTP/1.1 200 OK
54 | 	// Content-Length: 11
55 | 	// Content-Type: text/plain; charset=utf-8
56 | 	// Date: Wed, 01 Jan 2020 00:00:00 GMT
57 | 	//
58 | 	// hello world
59 | 	fmt.Printf("%q", dump)
60 | 	// Output:
61 | 	// "HTTP/1.1 200 OK\r\nContent-Length: 11\r\nContent-Type: text/plain; charset=utf-8\r\nDate: Wed, 01 Jan 2020 00:00:00 GMT\r\n\r\nhello world"
62 | }
63 | 
64 |

65 |

66 | by psampaz - 67 | source code - comment below or here 69 |

70 | 77 |
78 |
79 |
80 |
81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /docs/how-to-print-go-version.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to print Go version - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to print Go version

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"fmt"
25 | 	"runtime"
26 | )
27 | 
28 | func Example() {
29 | 	fmt.Printf("Go version: %s\n", runtime.Version())
30 | 	// Output:
31 | 	// Go version: go1.14.2
32 | }
33 | 
34 |

35 |

36 | by psampaz - 37 | source code - comment below or here 39 |

40 | 47 |
48 |
49 |
50 |
51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /docs/how-to-print-information-about-the-operating-system-architecture-and-pointer-size.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to print information about the operating system, architecture and pointer size - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to print information about the operating system, architecture and pointer size

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"fmt"
25 | 	"runtime"
26 | 	"unsafe"
27 | )
28 | 
29 | func Example() {
30 | 	fmt.Printf("running program's operating system target: %s\n", runtime.GOOS)
31 | 	fmt.Printf("running program's architecture target: %s\n", runtime.GOARCH)
32 | 	var ptr uintptr
33 | 	ptrSize := int(unsafe.Sizeof(ptr))
34 | 	fmt.Printf("pointer size: %d\n", ptrSize)
35 | 	// Output:
36 | 	// running program's operating system target: linux
37 | 	// running program's architecture target: amd64
38 | 	// pointer size: 8
39 | }
40 | 
41 |

42 |

43 | by psampaz - 44 | source code - comment below or here 46 |

47 | 54 |
55 |
56 |
57 |
58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /docs/how-to-print-the-binary-representation-of-an-integer.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to print the binary representation of an integer - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to print the binary representation of an integer

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"fmt"
25 | )
26 | 
27 | func Example() {
28 | 	// The %b verb print the binary representation of an integer
29 | 	for x := 0; x < 16; x++ {
30 | 		fmt.Printf("%b\n", x)
31 | 	}
32 | 	// If you want the output to have the same length, 8 bits for example
33 | 	// use the %08b notation which means:
34 | 	// print binary, use 8 digits for the output, pad with leading zeros
35 | 	fmt.Println("fixed length of 8 digits:")
36 | 	for x := 0; x < 16; x++ {
37 | 		fmt.Printf("%08b\n", x)
38 | 	}
39 | 	// Output:
40 | 	// 0
41 | 	// 1
42 | 	// 10
43 | 	// 11
44 | 	// 100
45 | 	// 101
46 | 	// 110
47 | 	// 111
48 | 	// 1000
49 | 	// 1001
50 | 	// 1010
51 | 	// 1011
52 | 	// 1100
53 | 	// 1101
54 | 	// 1110
55 | 	// 1111
56 | 	// fixed length of 8 digits:
57 | 	// 00000000
58 | 	// 00000001
59 | 	// 00000010
60 | 	// 00000011
61 | 	// 00000100
62 | 	// 00000101
63 | 	// 00000110
64 | 	// 00000111
65 | 	// 00001000
66 | 	// 00001001
67 | 	// 00001010
68 | 	// 00001011
69 | 	// 00001100
70 | 	// 00001101
71 | 	// 00001110
72 | 	// 00001111
73 | }
74 | 
75 |

76 |

77 | by psampaz - 78 | source code - comment below or here 80 |

81 | 88 |
89 |
90 |
91 |
92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /docs/how-to-print-the-same-variable-multiple-times-using-printf.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to print the same variable multiple times using printf - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to print the same variable multiple times using printf

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"fmt"
25 | )
26 | 
27 | func Example() {
28 | 	// You can print multiple times the same variable using argument indexes
29 | 	// The notation [n] before the verb, means use the nth argument after the format.
30 | 	// The above applies to Printf, Sprintf, and Fprintf
31 | 	fmt.Printf("%[1]d %[1]d\n", 5)
32 | 	fmt.Printf("%[2]d %[2]d %[1]d %[1]d\n", 5, 6)
33 | 	// Output:
34 | 	// 5 5
35 | 	// 6 6 5 5
36 | }
37 | 
38 |

39 |

40 | by psampaz - 41 | source code - comment below or here 43 |

44 | 51 |
52 |
53 |
54 |
55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/how-to-read-an-http-response-status-code.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to read an HTTP response status code - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to read an HTTP response status code

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"fmt"
25 | 	"net/http"
26 | 	"net/http/httptest"
27 | )
28 | 
29 | func Example() {
30 | 	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
31 | 		w.WriteHeader(http.StatusOK)
32 | 		w.Write([]byte("hello world"))
33 | 	}))
34 | 	defer ts.Close()
35 | 
36 | 	resp, err := http.Get(ts.URL)
37 | 	if err != nil {
38 | 		fmt.Println(err)
39 | 	}
40 | 	defer resp.Body.Close()
41 | 
42 | 	fmt.Printf("%s\n", resp.Status)
43 | 	fmt.Printf("%d\n", resp.StatusCode)
44 | 	// Output:
45 | 	// 200 OK
46 | 	// 200
47 | }
48 | 
49 |

50 |

51 | by psampaz - 52 | source code - comment below or here 54 |

55 | 62 |
63 |
64 |
65 |
66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /docs/how-to-test-a-function-that-panics.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | How to test a function that panics - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

How to test a function that panics

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import "testing"
24 | 
25 | func f(shouldPanic bool) string {
26 | 	if shouldPanic {
27 | 		panic("function panicked")
28 | 	}
29 | 	return "function didn't panic"
30 | }
31 | 
32 | func Test_f(t *testing.T) {
33 | 	t.Run("panics", func(t *testing.T) {
34 | 		// If the function panics, recover() will
35 | 		// return a non nil value.
36 | 		defer func() {
37 | 			if r := recover(); r == nil {
38 | 				t.Errorf("function should panic")
39 | 			}
40 | 		}()
41 | 
42 | 		f(true)
43 | 	})
44 | 
45 | 	t.Run("does not panic", func(t *testing.T) {
46 | 		shouldPanic := false
47 | 		want := "function didn't panic"
48 | 		if got := f(shouldPanic); got != want {
49 | 			t.Errorf("f(%v) = %v, want %v", shouldPanic, got, want)
50 | 		}
51 | 	})
52 | 
53 | }
54 | 
55 |

56 |

57 | by psampaz - 58 | source code - comment below or here 60 |

61 | 68 |
69 |
70 |
71 |
72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /docs/what-is-the-maximum-value-of-numeric-types.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | What is the maximum value of numeric types - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

What is the maximum value of numeric types

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 |

package main
22 | 
23 | import (
24 | 	"fmt"
25 | 	"math"
26 | )
27 | 
28 | func Example() {
29 | 	fmt.Println("Max int8:", math.MaxInt8)
30 | 	fmt.Println("Max int16:", math.MaxInt16)
31 | 	fmt.Println("Max int32:", math.MaxInt32)
32 | 	fmt.Println("Max int64:", math.MaxInt64)
33 | 	fmt.Println("Max uint8:", math.MaxUint8)
34 | 	fmt.Println("Max uint16:", math.MaxUint16)
35 | 	fmt.Println("Max uint32:", math.MaxUint32)
36 | 	// See https://github.com/golang/go/issues/19621
37 | 	fmt.Println("Max uint64:", uint64(math.MaxUint64))
38 | 	fmt.Println("Max float32:", math.MaxFloat32)
39 | 	fmt.Println("Max float64:", math.MaxFloat64)
40 | 	// Output:
41 | 	// Max int8: 127
42 | 	// Max int16: 32767
43 | 	// Max int32: 2147483647
44 | 	// Max int64: 9223372036854775807
45 | 	// Max uint8: 255
46 | 	// Max uint16: 65535
47 | 	// Max uint32: 4294967295
48 | 	// Max uint64: 18446744073709551615
49 | 	// Max float32: 3.4028234663852886e+38
50 | 	// Max float64: 1.7976931348623157e+308
51 | }
52 | 
53 |

54 |

55 | by psampaz - 56 | source code - comment below or here 58 |

59 | 66 |
67 |
68 |
69 |
70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /snippets/how-to-calculate-the-hamming-distance-between-two-strings/main_test.go: -------------------------------------------------------------------------------- 1 | // Strings: How to calculate the hamming distance between two strings 2 | package main 3 | 4 | import ( 5 | "errors" 6 | "testing" 7 | ) 8 | 9 | // https://en.wikipedia.org/wiki/Hamming_distance: 10 | // Τhe Hamming distance between two strings of equal length 11 | // is the number of positions at which the corresponding symbols are different. 12 | // In other words, it measures the minimum number of substitutions 13 | // required to change one string into the other 14 | // 15 | // Hamming distance function calculates the rune based 16 | // hamming distance between strings a and b 17 | func HammingDistance(a string, b string) (int, error) { 18 | // stings in Go are slices of bytes so we have first to convert them to runes 19 | // read more here https://blog.golang.org/strings 20 | ra := []rune(a) 21 | rb := []rune(b) 22 | if len(ra) != len(rb) { 23 | return 0, errors.New("strings do not have the same length") 24 | } 25 | 26 | var distance int 27 | for i := range ra { 28 | if rb[i] != ra[i] { 29 | distance++ 30 | } 31 | } 32 | return distance, nil 33 | } 34 | 35 | func TestHammingDistance(t *testing.T) { 36 | tests := []struct { 37 | name string 38 | a string 39 | b string 40 | want int 41 | wantErr bool 42 | }{ 43 | { 44 | name: "no equal length", 45 | a: "abc", 46 | b: "abcd", 47 | want: 0, 48 | wantErr: true, 49 | }, 50 | { 51 | name: "same strings ascii", 52 | a: "abcd", 53 | b: "abcd", 54 | want: 0, 55 | wantErr: false, 56 | }, 57 | { 58 | name: "one character different ascii", 59 | a: "Abcd", 60 | b: "abcd", 61 | want: 1, 62 | wantErr: false, 63 | }, 64 | { 65 | name: "all characters different ascii", 66 | a: "ABCD", 67 | b: "abcd", 68 | want: 4, 69 | wantErr: false, 70 | }, 71 | { 72 | name: "same strings utf8", 73 | a: "Καλημέρα", 74 | b: "Καλημέρα", 75 | want: 0, 76 | wantErr: false, 77 | }, 78 | { 79 | name: "one character different utf8", 80 | a: "Καλημέρα", 81 | b: "Καλημερα", 82 | want: 1, 83 | wantErr: false, 84 | }, 85 | { 86 | name: "all characters different utf8", 87 | a: "ΚΑΛΗΜΕΡΑ", 88 | b: "καλημέρα", 89 | want: 8, 90 | wantErr: false, 91 | }, 92 | } 93 | 94 | for _, tt := range tests { 95 | t.Run(tt.name, func(t *testing.T) { 96 | got, err := HammingDistance(tt.a, tt.b) 97 | if (err != nil) != tt.wantErr { 98 | t.Errorf( 99 | "HammingDistance(%s %s) error = %v, wantErr %v", tt.a, tt.b, err, tt.wantErr, 100 | ) 101 | return 102 | } 103 | if got != tt.want { 104 | t.Errorf("HammingDistance(%s %s) = %v, want %v", tt.a, tt.b, got, tt.want) 105 | } 106 | }) 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /snippets/how-to-calculate-the-hamming-distance-between-two-strings/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 8d4492ab8533c8f0c96feccc66d5463b1700249b7807a5bd76bf9499afc74f77 2 | playground_url: https://play.golang.org/p/DpHrFwnp6Kd 3 | issue_id: 45 4 | -------------------------------------------------------------------------------- /snippets/how-to-calculate-the-sum-of-multiple-numbers/main_test.go: -------------------------------------------------------------------------------- 1 | // Numbers: How to calculate the sum of multiple numbers 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "testing" 7 | ) 8 | 9 | // References: 10 | // https://golang.org/ref/spec#Passing_arguments_to_..._parameters 11 | func AddNumbers(s ...int) int { 12 | sum := 0 13 | for _, x := range s { 14 | sum += x 15 | } 16 | return sum 17 | } 18 | 19 | func TestAddNumbers(t *testing.T) { 20 | tests := []struct { 21 | name string 22 | s []int 23 | want int 24 | }{ 25 | { 26 | name: "nil", 27 | s: nil, 28 | want: 0, 29 | }, 30 | { 31 | name: "single number", 32 | s: []int{1}, 33 | want: 1, 34 | }, 35 | { 36 | name: "multiple numbers", 37 | s: []int{4, 3, 2, 1, 0}, 38 | want: 10, 39 | }, 40 | } 41 | for _, tt := range tests { 42 | t.Run(tt.name, func(t *testing.T) { 43 | if got := AddNumbers(tt.s...); got != tt.want { 44 | t.Errorf("AddNumbers(%v) = %v, want %v", tt.s, got, tt.want) 45 | } 46 | }) 47 | } 48 | } 49 | 50 | func ExampleAddNumbers() { 51 | fmt.Println(AddNumbers(4, 3, 2, 1, 0)) 52 | fmt.Println(AddNumbers([]int{4, 3, 2, 1, 0}...)) 53 | // Output: 54 | // 10 55 | // 10 56 | } 57 | -------------------------------------------------------------------------------- /snippets/how-to-calculate-the-sum-of-multiple-numbers/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 93f6ddc1d45ab2d4de618f30aee356936b19847a57cdd668bcce9e54db369127 2 | playground_url: https://play.golang.org/p/iqr6W72D3jw 3 | issue_id: 1 4 | -------------------------------------------------------------------------------- /snippets/how-to-check-if-a-slice-contains-a-specific-element/main_test.go: -------------------------------------------------------------------------------- 1 | // Slices: How to check if a slice contains a specific element 2 | package main 3 | 4 | import "testing" 5 | 6 | func SliceContains(s []int, x int) bool { 7 | if len(s) == 0 { 8 | return false 9 | } 10 | for k := range s { 11 | if s[k] == x { 12 | return true 13 | } 14 | } 15 | return false 16 | } 17 | 18 | func TestSliceContains(t *testing.T) { 19 | tests := []struct { 20 | name string 21 | s []int 22 | x int 23 | want bool 24 | }{ 25 | { 26 | name: "nil", 27 | s: nil, 28 | x: 1, 29 | want: false, 30 | }, 31 | { 32 | name: "empty", 33 | s: []int{}, 34 | x: 1, 35 | want: false, 36 | }, 37 | { 38 | name: "value exists", 39 | s: []int{2, 1}, 40 | x: 1, 41 | want: true, 42 | }, 43 | { 44 | name: "value does not exist", 45 | s: []int{2, 1}, 46 | x: 3, 47 | want: false, 48 | }, 49 | } 50 | for _, tt := range tests { 51 | t.Run(tt.name, func(t *testing.T) { 52 | if got := SliceContains(tt.s, tt.x); got != tt.want { 53 | t.Errorf("SliceContains(%v, %v) = %v, want %v", tt.s, tt.x, got, tt.want) 54 | } 55 | }) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /snippets/how-to-check-if-a-slice-contains-a-specific-element/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: eb3c87f85ba492536fd3dd532b2ec771f4d11524b437c0a6c88be1ef094c47d2 2 | playground_url: https://play.golang.org/p/fVpnCGA6mDk 3 | issue_id: 2 4 | -------------------------------------------------------------------------------- /snippets/how-to-check-if-a-string-ends-with-a-substring/main_test.go: -------------------------------------------------------------------------------- 1 | // Strings: How to check if a string ends with a substring 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | func Example() { 10 | fmt.Println(strings.HasSuffix("abcdefg", "fg")) 11 | fmt.Println(strings.HasSuffix("abcdefg", "Fg")) 12 | // Output: 13 | // true 14 | // false 15 | } 16 | -------------------------------------------------------------------------------- /snippets/how-to-check-if-a-string-ends-with-a-substring/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 20594f3fae34f41356bc35838dba341f9f78552df97c74d6defaf4de1814f5be 2 | playground_url: https://play.golang.org/p/LJkxZx3DsPs 3 | issue_id: 3 4 | -------------------------------------------------------------------------------- /snippets/how-to-check-if-a-string-is-lowercase/main_test.go: -------------------------------------------------------------------------------- 1 | // Strings: How to check if a string is lowercase 2 | package main 3 | 4 | import ( 5 | "testing" 6 | "unicode" 7 | ) 8 | 9 | func IsLowercase(s string) bool { 10 | if s == "" { 11 | return false 12 | } 13 | for _, c := range s { 14 | if !unicode.IsLower(c) { 15 | return false 16 | } 17 | } 18 | return true 19 | } 20 | 21 | func Test_IsLowercase(t *testing.T) { 22 | tests := []struct { 23 | name string 24 | s string 25 | want bool 26 | }{ 27 | { 28 | name: "empty", 29 | s: "", 30 | want: false, 31 | }, 32 | { 33 | name: "all lowercase", 34 | s: "abc", 35 | want: true, 36 | }, 37 | { 38 | name: "one uppercase", 39 | s: "abcD", 40 | want: false, 41 | }, 42 | { 43 | name: "all uppercase", 44 | s: "ABCDᾺ", 45 | want: false, 46 | }, 47 | } 48 | for _, tt := range tests { 49 | t.Run(tt.name, func(t *testing.T) { 50 | if got := IsLowercase(tt.s); got != tt.want { 51 | t.Errorf("IsLowercase(%q) = %v, want %v", tt.s, got, tt.want) 52 | } 53 | }) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /snippets/how-to-check-if-a-string-is-lowercase/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: d1f11952bf351c208b8f28b2e908f9fca39c333cee961d3f77d073d7093a70f3 2 | playground_url: https://play.golang.org/p/PJApKFwwAxM 3 | issue_id: 4 4 | -------------------------------------------------------------------------------- /snippets/how-to-check-if-a-string-is-uppercase/main_test.go: -------------------------------------------------------------------------------- 1 | // Strings: How to check if a string is uppercase 2 | package main 3 | 4 | import ( 5 | "testing" 6 | "unicode" 7 | ) 8 | 9 | func IsUppercase(s string) bool { 10 | if s == "" { 11 | return false 12 | } 13 | for _, c := range s { 14 | if !unicode.IsUpper(c) { 15 | return false 16 | } 17 | } 18 | return true 19 | } 20 | 21 | func Test_IsUppercase(t *testing.T) { 22 | tests := []struct { 23 | name string 24 | s string 25 | want bool 26 | }{ 27 | { 28 | name: "empty", 29 | s: "", 30 | want: false, 31 | }, 32 | { 33 | name: "all lowercase", 34 | s: "abc", 35 | want: false, 36 | }, 37 | { 38 | name: "one lowecase", 39 | s: "ABCd", 40 | want: false, 41 | }, 42 | { 43 | name: "all uppercase", 44 | s: "ABCD", 45 | want: true, 46 | }, 47 | } 48 | for _, tt := range tests { 49 | t.Run(tt.name, func(t *testing.T) { 50 | if got := IsUppercase(tt.s); got != tt.want { 51 | t.Errorf("IsUppercase(%q) = %v, want %v", tt.s, got, tt.want) 52 | } 53 | }) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /snippets/how-to-check-if-a-string-is-uppercase/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 72098cd3921f0320e757b6acc143acf5fa89837d24baf3bbee90c17270e0c1e3 2 | playground_url: https://play.golang.org/p/QLdK2CVlUlE 3 | issue_id: 5 4 | -------------------------------------------------------------------------------- /snippets/how-to-check-if-a-string-starts-with-substring/main_test.go: -------------------------------------------------------------------------------- 1 | // Strings: How to check if a string starts with substring 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | func Example() { 10 | fmt.Println(strings.HasPrefix("abcdefg", "ab")) 11 | fmt.Println(strings.HasPrefix("abcdefg", "Ab")) 12 | // Output: 13 | // true 14 | // false 15 | } 16 | -------------------------------------------------------------------------------- /snippets/how-to-check-if-a-string-starts-with-substring/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: e5d9bfd8fa2daa390bd4de4bd1301b04e0c922c54694898efd3c4c1e9e1429e6 2 | playground_url: https://play.golang.org/p/XrO9ieI8etB 3 | issue_id: 6 4 | -------------------------------------------------------------------------------- /snippets/how-to-check-if-a-type-satisfies-an-interface-at-runtime/main_test.go: -------------------------------------------------------------------------------- 1 | // Interfaces: How to check if a type satisfies an interface at runtime 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | type Checker interface { 9 | Check() bool 10 | } 11 | 12 | type P struct{} 13 | 14 | func (p *P) Check() bool { 15 | return true 16 | } 17 | 18 | type V struct{} 19 | 20 | func (v V) Check() bool { 21 | return true 22 | } 23 | 24 | type N struct{} 25 | 26 | // References: 27 | // https://golang.org/ref/spec#Method_sets 28 | // https://golang.org/ref/spec#Type_assertions 29 | // https://www.ardanlabs.com/blog/2017/07/interface-semantics.html 30 | func Example() { 31 | // According to the Go language specification: 32 | // A type may have a method set associated with it. 33 | // The method set of an interface type is its interface. 34 | // The method set of any other type T consists of all methods 35 | // declared with receiver type T. 36 | // The method set of the corresponding pointer type *T is 37 | // the set of all methods declared 38 | // with receiver *T or T (that is, it also contains the method set of T). 39 | // 40 | // In other words: 41 | // A type T satisfies an interface only if the interface methods are 42 | // implemented using value receiver. 43 | // A type *T satisfies an interface only if the interface methods are 44 | // implemented using value or pointer receiver 45 | 46 | // P implements the Checker interface using pointer receiver (*P) 47 | // so *P satisfies the checker interface 48 | // we assign the value &P to an empty interface 49 | var pp interface{} = &P{} 50 | // we use type assertion to check if the value of the interface is type Checker 51 | if _, ok := pp.(Checker); ok { 52 | fmt.Println("*P implements the checker interface") 53 | } else { 54 | fmt.Println("*P does not implement the checker interface") 55 | } 56 | 57 | // P implements the Checker interface using pointer receiver (*P) 58 | // so P does not satisfy the checker interface 59 | var pv interface{} = P{} 60 | 61 | if _, ok := pv.(Checker); ok { 62 | fmt.Println("P implements the checker interface") 63 | } else { 64 | fmt.Println("P does not implement the checker interface") 65 | } 66 | 67 | // V implements the Checker interface using value receiver 68 | // so *V satisfies the interface 69 | var vp interface{} = &V{} 70 | 71 | if _, ok := vp.(Checker); ok { 72 | fmt.Println("*V implements the checker interface") 73 | } else { 74 | fmt.Println("*V does not implement the checker interface") 75 | } 76 | 77 | // V implements the Checker interface using value receiver 78 | // so V satisfies the interface 79 | var vv interface{} = V{} 80 | 81 | if _, ok := vv.(Checker); ok { 82 | fmt.Println("V implements the checker interface") 83 | } else { 84 | fmt.Println("V does not implement the checker interface") 85 | } 86 | 87 | // N does not implement the Checker interface at all 88 | // so *N does not satisfy the interface 89 | var np interface{} = &N{} 90 | 91 | if _, ok := np.(Checker); ok { 92 | fmt.Println("*N implements the checker interface") 93 | } else { 94 | fmt.Println("*N does not implement the checker interface") 95 | } 96 | 97 | // N does not implement the Checker interface at all 98 | // so N does not satisfy the interface 99 | var nv interface{} = N{} 100 | 101 | if _, ok := nv.(Checker); ok { 102 | fmt.Println("N implements the checker interface") 103 | } else { 104 | fmt.Println("N does not implement the checker interface") 105 | } 106 | // Output: 107 | // *P implements the checker interface 108 | // P does not implement the checker interface 109 | // *V implements the checker interface 110 | // V implements the checker interface 111 | // *N does not implement the checker interface 112 | // N does not implement the checker interface 113 | } 114 | -------------------------------------------------------------------------------- /snippets/how-to-check-if-a-type-satisfies-an-interface-at-runtime/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 1d4824293348533a559d6efb2f02ef1dfd2b15dbc1825098e3968d225f322faa 2 | playground_url: https://play.golang.org/p/LgFrZxdFGbW 3 | issue_id: 32 4 | -------------------------------------------------------------------------------- /snippets/how-to-check-if-string-is-valid-json/main_test.go: -------------------------------------------------------------------------------- 1 | // Strings: How to check if string is valid JSON 2 | package main 3 | 4 | import ( 5 | "encoding/json" 6 | "fmt" 7 | ) 8 | 9 | func Example() { 10 | valid := `{"foo":"bar"}` 11 | invalid := `}{` 12 | 13 | fmt.Println(json.Valid([]byte(valid))) 14 | fmt.Println(json.Valid([]byte(invalid))) 15 | // Output: 16 | // true 17 | // false 18 | } 19 | -------------------------------------------------------------------------------- /snippets/how-to-check-if-string-is-valid-json/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: c472418c9f1e2b0a89974d75948cbb777418b8f8270fe5ecb9be272487c1a49a 2 | playground_url: https://play.golang.org/p/rmpr3toMaMs 3 | issue_id: 7 4 | -------------------------------------------------------------------------------- /snippets/how-to-check-that-a-time-value-is-a-specific-day-of-the-week/main_test.go: -------------------------------------------------------------------------------- 1 | // Time: How to check that a time value is a specific day of the week 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "time" 7 | ) 8 | 9 | func Example() { 10 | // The time package offers a time.Weekday() method which returns 11 | // a time.Weekday value https://pkg.go.dev/time?tab=doc#Weekday 12 | now := time.Now() 13 | if now.Weekday() == time.Tuesday { 14 | fmt.Println("The day on Go playground is always Tuesday") 15 | } 16 | // Output: 17 | // The day on Go playground is always Tuesday 18 | } 19 | -------------------------------------------------------------------------------- /snippets/how-to-check-that-a-time-value-is-a-specific-day-of-the-week/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 4f72dbb23082a9850179a9147d35e2824ac15c5c46af5365645cdce55c45c708 2 | playground_url: https://play.golang.org/p/9OyXJGI-0IO 3 | issue_id: 63 4 | -------------------------------------------------------------------------------- /snippets/how-to-concatenate-strings/main_test.go: -------------------------------------------------------------------------------- 1 | // Strings: How to concatenate strings 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | func Example() { 10 | // Create a slice of the strings that you want to join together 11 | strs := []string{"aa", "bb", "cc"} 12 | //Use the strings.Join function to join them, by passing the desired separator 13 | fmt.Println(strings.Join(strs, "-")) 14 | fmt.Println(strings.Join(strs, ", ")) 15 | fmt.Println(strings.Join(strs, "")) 16 | // Output: 17 | // aa-bb-cc 18 | // aa, bb, cc 19 | // aabbcc 20 | } 21 | -------------------------------------------------------------------------------- /snippets/how-to-concatenate-strings/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 89d798a1185679b076fec2435c32d8997cad646db9a11a480423dc8be4b93539 2 | playground_url: https://play.golang.org/p/Kza4Mhwpinm 3 | issue_id: 8 4 | -------------------------------------------------------------------------------- /snippets/how-to-convert-int-to-string/main_test.go: -------------------------------------------------------------------------------- 1 | // Conversions: How to convert int to string 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "strconv" 7 | ) 8 | 9 | func Example_itoa() { 10 | // Converting an int to a string can be done 11 | // using the `strconv.Itoa` (integer to ascii) function 12 | a := strconv.Itoa(1234) 13 | fmt.Printf("%q\n", a) 14 | // Output: 15 | // "1234" 16 | } 17 | 18 | func Example_formatInt() { 19 | // `strconv.Itoa` is calls internally 20 | // `FormatInt(int64(i), 10)` so another way 21 | // to convert an int to a string is the following: 22 | b := strconv.FormatInt(int64(1234), 10) 23 | fmt.Printf("%q\n", b) 24 | // Output: 25 | // "1234" 26 | } 27 | 28 | func Example_sprintf() { 29 | // A third way would be to use the `fmt.Sprintf` method: 30 | c := fmt.Sprintf("%d", 1234) 31 | fmt.Printf("%q\n", c) 32 | // Output: 33 | // "1234" 34 | } 35 | -------------------------------------------------------------------------------- /snippets/how-to-convert-int-to-string/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 2fd92b1cde0f36c9a88af08f8b0ad44177ac1fd5368f618f22677b626d90c53d 2 | playground_url: https://play.golang.org/p/1sSf6UxQCes 3 | issue_id: 9 4 | -------------------------------------------------------------------------------- /snippets/how-to-copy-a-map/main_test.go: -------------------------------------------------------------------------------- 1 | // Maps: How to copy a map 2 | package main 3 | 4 | import ( 5 | "reflect" 6 | "testing" 7 | ) 8 | 9 | func CopyMap(src map[string]string) map[string]string { 10 | if src == nil { 11 | return nil 12 | } 13 | // Initialize a new map 14 | dst := make(map[string]string) 15 | // range through the source map 16 | // and copy each element to the new one 17 | for k, v := range src { 18 | dst[k] = v 19 | } 20 | return dst 21 | } 22 | 23 | func TestCopyMap(t *testing.T) { 24 | tests := []struct { 25 | name string 26 | src map[string]string 27 | want map[string]string 28 | }{ 29 | { 30 | name: "nil map", 31 | src: nil, 32 | want: nil, 33 | }, 34 | { 35 | name: "empty map", 36 | src: make(map[string]string), 37 | want: make(map[string]string), 38 | }, 39 | { 40 | name: "non empty map", 41 | src: map[string]string{ 42 | "a": "a", 43 | "b": "b", 44 | }, 45 | want: map[string]string{ 46 | "a": "a", 47 | "b": "b", 48 | }, 49 | }, 50 | } 51 | for _, tt := range tests { 52 | t.Run(tt.name, func(t *testing.T) { 53 | if got := CopyMap(tt.src); !reflect.DeepEqual(got, tt.want) { 54 | t.Errorf("CopyMap(%v) = %v, want %v", tt.src, got, tt.want) 55 | } 56 | }) 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /snippets/how-to-copy-a-map/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: e7cb82e767e7ac7da1e7fea3e7192de8f14f98c9bc2f11316d30dd606bc278e1 2 | playground_url: https://play.golang.org/p/GRIciGtgI6U 3 | issue_id: 25 4 | -------------------------------------------------------------------------------- /snippets/how-to-count-the-number-of-words-in-a-string/main_test.go: -------------------------------------------------------------------------------- 1 | // Strings: How to count the number of words in a string 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | // strings.Fields() splits a string around one or more 10 | // consecutive whitespaces (https://golang.org/pkg/unicode/#IsSpace) 11 | // The number of fields is the actual number of words 12 | func CountWords(s string) int { 13 | return len(strings.Fields(s)) 14 | } 15 | 16 | // If the words are not separated by whitespaces 17 | // but with comma (a csv row for example) or whatever else, 18 | // you can use the strings.FieldsFunc() and explicitly define 19 | // the points of split 20 | func CountWordsFunc(s string, f func(rune) bool) int { 21 | return len(strings.FieldsFunc(s, f)) 22 | } 23 | 24 | func ExampleCountWords() { 25 | wc := CountWords(" How to count words? \n") 26 | fmt.Println(wc) 27 | // Output: 28 | // 4 29 | } 30 | 31 | func ExampleCountWordsFunc() { 32 | f := func(c rune) bool { 33 | return c == ',' 34 | } 35 | wc := CountWordsFunc("word1, word2, word3", f) 36 | fmt.Println(wc) 37 | // Output: 38 | // 3 39 | } 40 | -------------------------------------------------------------------------------- /snippets/how-to-count-the-number-of-words-in-a-string/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: bd55600a83ba5ec2b7ee79880e9369c9d0e2d0a19c77d294ee070eb51652a3d1 2 | playground_url: https://play.golang.org/p/nMJ737zP029 3 | issue_id: 46 4 | -------------------------------------------------------------------------------- /snippets/how-to-create-a-set-using-a-map/main_test.go: -------------------------------------------------------------------------------- 1 | // Maps: How to create a set using a map 2 | package main 3 | 4 | import "fmt" 5 | 6 | // A set is a unordered collection of unique data. 7 | // Go does not have a built-in set data structure 8 | // but you can easily create one using a map 9 | func Example() { 10 | // The map keys are a unique unordered collection. 11 | // So if you just ignore the values, a map can be viewed as a set 12 | // The most space optimized way to do this is to use the empty struct 13 | // as the map value type, since the empty struct (a struct with no fields) 14 | // occupies zero bytes of storage 15 | // https://dave.cheney.net/2014/03/25/the-empty-struct 16 | set := make(map[string]struct{}) 17 | fmt.Println(set) 18 | // Add new elements in the set 19 | set["a"] = struct{}{} 20 | set["b"] = struct{}{} 21 | set["c"] = struct{}{} 22 | fmt.Println(set) 23 | 24 | // Check if an element exists in the set 25 | if _, exists := set["a"]; exists { 26 | fmt.Println("a exists in the set") 27 | } 28 | // Delete an element from the set 29 | delete(set, "b") 30 | fmt.Println(set) 31 | // Output: 32 | // map[] 33 | // map[a:{} b:{} c:{}] 34 | // a exists in the set 35 | // map[a:{} c:{}] 36 | } 37 | -------------------------------------------------------------------------------- /snippets/how-to-create-a-set-using-a-map/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: d5d9290b338ddec0238fad2e057ce50b6bc1a8163e43c259a0d5922763d8ae1a 2 | playground_url: https://play.golang.org/p/fGL3vnPcdXn 3 | issue_id: 26 4 | -------------------------------------------------------------------------------- /snippets/how-to-create-multiple-loggers/main_test.go: -------------------------------------------------------------------------------- 1 | // Logging: How to create multiple loggers 2 | package main 3 | 4 | import ( 5 | "log" 6 | "os" 7 | ) 8 | 9 | func Example() { 10 | // You can create as many loggers you want using the log.New method 11 | // Each logger can write logs in different targets, use different prefix 12 | // and different settings 13 | logger1 := log.New(os.Stdout, "logger1: ", log.LstdFlags) 14 | logger2 := log.New(os.Stdout, "logger2: ", log.LstdFlags|log.Lmicroseconds) 15 | logger1.Println("Message from logger1") 16 | logger2.Println("Message from logger2") 17 | // Output: 18 | // logger1: 2009/11/10 23:00:00 Message from logger1 19 | // logger2: 2009/11/10 23:00:00.000000 Message from logger2 20 | } 21 | -------------------------------------------------------------------------------- /snippets/how-to-create-multiple-loggers/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 448a48195604ad3bb89082cf714a9ed43ed62f6ab6d7633253580a4ba9cfc277 2 | playground_url: https://play.golang.org/p/sSKvRejFoww 3 | issue_id: 64 4 | -------------------------------------------------------------------------------- /snippets/how-to-define-a-custom-string-representation-for-a-type/main_test.go: -------------------------------------------------------------------------------- 1 | // Strings: How to define a custom string representation for a type 2 | // 3 | // To control the string representation of a type 4 | // the type needs to implement the Stringer interface 5 | // https://pkg.go.dev/fmt?tab=doc#Stringer 6 | // type Stringer interface { 7 | // String() string 8 | // } 9 | // The String method is used to print values passed as an operand 10 | // to any format that accepts a string or to an unformatted printer 11 | // such as Print. 12 | package main 13 | 14 | import "fmt" 15 | 16 | // UserA does not implement the Stringer interface 17 | type UserA struct { 18 | FirstName string 19 | LastName string 20 | } 21 | 22 | // UserB implements the Stringer interface 23 | type UserB struct { 24 | FirstName string 25 | LastName string 26 | } 27 | 28 | func (u UserB) String() string { 29 | return fmt.Sprintf("First name is %s, last name is %s", u.FirstName, u.LastName) 30 | } 31 | 32 | // BoolA does implements the Stringer interface 33 | type BoolA bool 34 | 35 | // BoolB implements the Stringer interface 36 | type BoolB bool 37 | 38 | func (b BoolB) String() string { 39 | if b { 40 | return "Yes" 41 | } else { 42 | return "No" 43 | } 44 | } 45 | 46 | func Example() { 47 | a := UserA{"John", "Doe"} 48 | b := UserB{"John", "Doe"} 49 | c := BoolA(true) 50 | d := BoolB(true) 51 | 52 | fmt.Println(a) 53 | fmt.Println(b) 54 | fmt.Println(c) 55 | fmt.Println(d) 56 | // Output: 57 | // {John Doe} 58 | // First name is John, last name is Doe 59 | // true 60 | // Yes 61 | } 62 | -------------------------------------------------------------------------------- /snippets/how-to-define-a-custom-string-representation-for-a-type/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 4f96aafd249082c9d82642e6302a0628bf49c77a38ad9e2691966116264be56c 2 | playground_url: https://play.golang.org/p/7gtVkS3hD1s 3 | issue_id: 65 4 | -------------------------------------------------------------------------------- /snippets/how-to-delete-an-element-from-a-slice/main_test.go: -------------------------------------------------------------------------------- 1 | // Slices: How to delete an element from a slice 2 | package main 3 | 4 | import ( 5 | "errors" 6 | "reflect" 7 | "testing" 8 | ) 9 | 10 | // DeleteSlice removes an element at a specific index of an slice. 11 | // An error is return in case the index is out of bounds or if the slice is nil or empty. 12 | func DeleteSlice(s []int, i int) ([]int, error) { 13 | if len(s) == 0 { 14 | return nil, errors.New("Cannot delete an element from a nil or empty slice") 15 | } 16 | if i < 0 || i > len(s)-1 { 17 | return nil, errors.New("Index out of bounds") 18 | } 19 | 20 | return append(s[:i], s[i+1:]...), nil 21 | } 22 | 23 | func TestDeleteInt(t *testing.T) { 24 | tests := []struct { 25 | name string 26 | s []int 27 | i int 28 | want []int 29 | wantErr bool 30 | }{ 31 | { 32 | name: "nil slice", 33 | s: nil, 34 | i: 0, 35 | want: nil, 36 | wantErr: true, 37 | }, 38 | { 39 | name: "empty slice", 40 | s: []int{}, 41 | i: 0, 42 | want: nil, 43 | wantErr: true, 44 | }, 45 | { 46 | name: "non empty slice. Index larger than len(a)-1", 47 | s: []int{1, 2, 3, 4, 5}, 48 | i: 5, 49 | want: nil, 50 | wantErr: true, 51 | }, 52 | { 53 | name: "non empty slice. Index < 0", 54 | s: []int{1, 2, 3, 4, 5}, 55 | i: -1, 56 | want: nil, 57 | wantErr: true, 58 | }, 59 | { 60 | name: "non empty slice", 61 | s: []int{1, 2, 3, 4, 5}, 62 | i: 2, 63 | want: []int{1, 2, 4, 5}, 64 | wantErr: false, 65 | }, 66 | } 67 | 68 | for _, tt := range tests { 69 | t.Run(tt.name, func(t *testing.T) { 70 | got, err := DeleteSlice(tt.s, tt.i) 71 | if (err != nil) != tt.wantErr { 72 | t.Errorf("DeleteSlice() error = %v, wantErr %v", err, tt.wantErr) 73 | return 74 | } 75 | if !reflect.DeepEqual(got, tt.want) { 76 | t.Errorf("DeleteSlice() = %v, want %v", got, tt.want) 77 | } 78 | }) 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /snippets/how-to-delete-an-element-from-a-slice/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 941a9d6b4ade226f5b601ea658b28554d47fa4678fdf946637e575becb87e3d6 2 | playground_url: https://play.golang.org/p/9ci_t8ZyRcg 3 | issue_id: 54 4 | -------------------------------------------------------------------------------- /snippets/how-to-disable-log-output/main_test.go: -------------------------------------------------------------------------------- 1 | // Logging: How to disable log output 2 | package main 3 | 4 | import ( 5 | "io/ioutil" 6 | "log" 7 | ) 8 | 9 | func Example() { 10 | // If you want to disable log output (during test for example) 11 | // you have to set the logger ouput to ioutil.Discard 12 | // which is an io.Writer on which all Write calls succeed 13 | // without doing anything 14 | log.SetOutput(ioutil.Discard) 15 | log.Println("log disabled") 16 | // Output: 17 | // 18 | } 19 | -------------------------------------------------------------------------------- /snippets/how-to-disable-log-output/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 5d70534daf7c7b2ee41717c4bb6e7916d47f1a973f50fdfc936e20c9807f808e 2 | playground_url: https://play.golang.org/p/GS9rJkFVnr4 3 | issue_id: 67 4 | -------------------------------------------------------------------------------- /snippets/how-to-filter-a-slice/main_test.go: -------------------------------------------------------------------------------- 1 | // Slices: How to filter a slice 2 | package main 3 | 4 | import ( 5 | "reflect" 6 | "testing" 7 | ) 8 | 9 | // FilterSlice filters a slice based on a predicate 10 | func FilterSlice(s []int, keep func(x int) bool) []int { 11 | if len(s) == 0 { 12 | return s 13 | } 14 | 15 | n := 0 16 | for _, v := range s { 17 | if keep(v) { 18 | s[n] = v 19 | n++ 20 | } 21 | } 22 | 23 | return s[:n] 24 | } 25 | 26 | func TestFilterInt(t *testing.T) { 27 | tests := []struct { 28 | name string 29 | s []int 30 | keep func(x int) bool 31 | want []int 32 | }{ 33 | { 34 | name: "nil slice", 35 | s: nil, 36 | keep: func(int) bool { panic("not implemented") }, 37 | want: nil, 38 | }, 39 | { 40 | name: "empty slice", 41 | s: []int{}, 42 | keep: func(int) bool { panic("not implemented") }, 43 | want: []int{}, 44 | }, 45 | { 46 | name: "non empty slice", 47 | s: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 48 | keep: func(x int) bool { 49 | return x < 5 50 | }, 51 | want: []int{1, 2, 3, 4}, 52 | }, 53 | } 54 | for _, tt := range tests { 55 | t.Run(tt.name, func(t *testing.T) { 56 | if got := FilterSlice(tt.s, tt.keep); !reflect.DeepEqual(got, tt.want) { 57 | t.Errorf("FilterSlice() = %v, want %v", got, tt.want) 58 | } 59 | }) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /snippets/how-to-filter-a-slice/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: b083b3415b4e7c134c7f2e7fe464371422d597db6af9fa94517dcef2e6d319b3 2 | playground_url: https://play.golang.org/p/gExArA6On-d 3 | issue_id: 55 4 | -------------------------------------------------------------------------------- /snippets/how-to-find-the-maximum-element-of-a-slice/main_test.go: -------------------------------------------------------------------------------- 1 | // Slices: How to find the maximum element of a slice 2 | package main 3 | 4 | import ( 5 | "errors" 6 | "testing" 7 | ) 8 | 9 | // MaxSlice return the maximum element of slice s 10 | // or an error in case the s is nil or empty 11 | func MaxSlice(s []int) (int, error) { 12 | if len(s) == 0 { 13 | return 0, errors.New("cannot find the maximum of a nil or empty slice") 14 | } 15 | 16 | max := s[0] 17 | for k := range s { 18 | if s[k] > max { 19 | max = s[k] 20 | } 21 | } 22 | 23 | return max, nil 24 | } 25 | 26 | func TestMaxSlice(t *testing.T) { 27 | tests := []struct { 28 | name string 29 | s []int 30 | want int 31 | wantErr bool 32 | }{ 33 | { 34 | name: "nil", 35 | s: nil, 36 | want: 0, 37 | wantErr: true, 38 | }, 39 | { 40 | name: "empty", 41 | s: []int{}, 42 | want: 0, 43 | wantErr: true, 44 | }, 45 | { 46 | name: "non empty slice", 47 | s: []int{1, 4, 5, -34, 2, 100}, 48 | want: 100, 49 | wantErr: false, 50 | }, 51 | } 52 | for _, tt := range tests { 53 | t.Run(tt.name, func(t *testing.T) { 54 | got, err := MaxSlice(tt.s) 55 | if (err != nil) != tt.wantErr { 56 | t.Errorf("MaxSlice(%#v) error = %v, wantErr %v", tt.s, err, tt.wantErr) 57 | return 58 | } 59 | if got != tt.want { 60 | t.Errorf("MaxSlice(%#v) = %v, want %v", tt.s, got, tt.want) 61 | } 62 | }) 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /snippets/how-to-find-the-maximum-element-of-a-slice/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: b8c92b9249643997149faf2fffcf10883362b133642c64003323c57df92d6cf4 2 | playground_url: https://play.golang.org/p/vRv5Fm6S57U 3 | issue_id: 10 4 | -------------------------------------------------------------------------------- /snippets/how-to-find-the-minimum-element-of-a-slice/main_test.go: -------------------------------------------------------------------------------- 1 | // Slices: How to find the minimum element of a slice 2 | package main 3 | 4 | import ( 5 | "errors" 6 | "testing" 7 | ) 8 | 9 | // MaxSlice return the minimum element of slice s 10 | // or an error in case the s is nil or empty 11 | func MinSlice(s []int) (int, error) { 12 | if len(s) == 0 { 13 | return 0, errors.New("cannot find the minimum of a nil or empty slice") 14 | } 15 | 16 | min := s[0] 17 | for k := range s { 18 | if s[k] < min { 19 | min = s[k] 20 | } 21 | } 22 | 23 | return min, nil 24 | } 25 | 26 | func TestMinSlice(t *testing.T) { 27 | tests := []struct { 28 | name string 29 | s []int 30 | want int 31 | wantErr bool 32 | }{ 33 | { 34 | name: "nil", 35 | s: nil, 36 | want: 0, 37 | wantErr: true, 38 | }, 39 | { 40 | name: "empty", 41 | s: []int{}, 42 | want: 0, 43 | wantErr: true, 44 | }, 45 | { 46 | name: "non empty slice", 47 | s: []int{1, 3, 2, -4, 6, 5}, 48 | want: -4, 49 | wantErr: false, 50 | }, 51 | } 52 | for _, tt := range tests { 53 | t.Run(tt.name, func(t *testing.T) { 54 | got, err := MinSlice(tt.s) 55 | if (err != nil) != tt.wantErr { 56 | t.Errorf("MinSlice(%#v) error = %v, wantErr %v", tt.s, err, tt.wantErr) 57 | return 58 | } 59 | if got != tt.want { 60 | t.Errorf("MaxSlice(%#v) = %v, want %v", tt.s, got, tt.want) 61 | } 62 | }) 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /snippets/how-to-find-the-minimum-element-of-a-slice/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: a09a8f54de2878a4da563f0dc2e6ad926c4b8f1834e0012e1587c0ea12a375d8 2 | playground_url: https://play.golang.org/p/q6nFhcy1cF6 3 | issue_id: 11 4 | -------------------------------------------------------------------------------- /snippets/how-to-format-go-code-programmatically/main_test.go: -------------------------------------------------------------------------------- 1 | // Other: How to format Go code programmatically 2 | // 3 | // Code can be formatted programmatically in the same way like running go fmt, 4 | // using the go/format package 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | "go/format" 10 | "log" 11 | ) 12 | 13 | func Example() { 14 | unformatted := ` 15 | package main 16 | import "fmt" 17 | 18 | func main( ) { 19 | x := 12 20 | fmt.Printf( "%d", x ) 21 | } 22 | 23 | 24 | ` 25 | formatted, err := format.Source([]byte(unformatted)) 26 | if err != nil { 27 | log.Fatal(err) 28 | } 29 | fmt.Printf("%s", string(formatted)) 30 | // Output: 31 | // package main 32 | // 33 | // import "fmt" 34 | // 35 | // func main() { 36 | // x := 12 37 | // fmt.Printf("%d", x) 38 | // } 39 | } 40 | -------------------------------------------------------------------------------- /snippets/how-to-format-go-code-programmatically/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: ae8c83f11caa818e3d4deee9322b2cb5fbb8bc9184c6a8226f5e628177399bec 2 | playground_url: https://play.golang.org/p/HFeO4FM33wd 3 | issue_id: 12 4 | -------------------------------------------------------------------------------- /snippets/how-to-get-the-md5-checksum-of-a-string/main_test.go: -------------------------------------------------------------------------------- 1 | // Strings: How to get the md5 checksum of a string 2 | package main 3 | 4 | import ( 5 | "crypto/md5" 6 | "fmt" 7 | "testing" 8 | ) 9 | 10 | func md5Checksum(s string) string { 11 | return fmt.Sprintf("%x", md5.Sum([]byte(s))) 12 | } 13 | 14 | func Test_md5Checksum(t *testing.T) { 15 | tests := []struct { 16 | name string 17 | s string 18 | want string 19 | }{ 20 | { 21 | name: "empty string", 22 | s: "", 23 | want: "d41d8cd98f00b204e9800998ecf8427e", 24 | }, 25 | { 26 | name: "hello world", 27 | s: "hello world", 28 | want: "5eb63bbbe01eeed093cb22bb8f5acdc3", 29 | }, 30 | } 31 | for _, tt := range tests { 32 | t.Run(tt.name, func(t *testing.T) { 33 | if got := md5Checksum(tt.s); got != tt.want { 34 | t.Errorf("md5Checksum(%q) = %v, want %v", tt.s, got, tt.want) 35 | } 36 | }) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /snippets/how-to-get-the-md5-checksum-of-a-string/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: df979e11f84367d0db1e9bd93305ed29e7e1c2e1b60f045a52f35bc1b58315bd 2 | playground_url: https://play.golang.org/p/64n4zakBte- 3 | issue_id: 13 4 | -------------------------------------------------------------------------------- /snippets/how-to-get-the-sha1-checksum-of-a-string/main_test.go: -------------------------------------------------------------------------------- 1 | // Strings: How to get the sha1 checksum of a string 2 | package main 3 | 4 | import ( 5 | "crypto/sha1" 6 | "fmt" 7 | "testing" 8 | ) 9 | 10 | func Sha1Checksum(s string) string { 11 | return fmt.Sprintf("%x", sha1.Sum([]byte(s))) 12 | } 13 | 14 | func Test_Sha1Checksum(t *testing.T) { 15 | tests := []struct { 16 | name string 17 | s string 18 | want string 19 | }{ 20 | { 21 | name: "empty string", 22 | s: "", 23 | want: "da39a3ee5e6b4b0d3255bfef95601890afd80709", 24 | }, 25 | { 26 | name: "hello world", 27 | s: "hello world", 28 | want: "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed", 29 | }, 30 | } 31 | for _, tt := range tests { 32 | t.Run(tt.name, func(t *testing.T) { 33 | if got := Sha1Checksum(tt.s); got != tt.want { 34 | t.Errorf("Sha1Checksum(%q) = %v, want %v", tt.s, got, tt.want) 35 | } 36 | }) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /snippets/how-to-get-the-sha1-checksum-of-a-string/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 704539243d28bc39da2f1fbddf0a671e285024871f060be67b6a9574fa215159 2 | playground_url: https://play.golang.org/p/MmyYy8xFNwB 3 | issue_id: 14 4 | -------------------------------------------------------------------------------- /snippets/how-to-get-the-sha256-checksum-of-a-string/main_test.go: -------------------------------------------------------------------------------- 1 | // Strings: How to get the sha256 checksum of a string 2 | package main 3 | 4 | import ( 5 | "crypto/sha256" 6 | "fmt" 7 | "testing" 8 | ) 9 | 10 | func Sha256Checksum(s string) string { 11 | return fmt.Sprintf("%x", sha256.Sum256([]byte(s))) 12 | } 13 | 14 | func Test_Sha256Checksum(t *testing.T) { 15 | tests := []struct { 16 | name string 17 | s string 18 | want string 19 | }{ 20 | { 21 | name: "empty string", 22 | s: "", 23 | want: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", 24 | }, 25 | { 26 | name: "hello world", 27 | s: "hello world", 28 | want: "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9", 29 | }, 30 | } 31 | for _, tt := range tests { 32 | t.Run(tt.name, func(t *testing.T) { 33 | if got := Sha256Checksum(tt.s); got != tt.want { 34 | t.Errorf("Sha256Checksum(%q) = %v, want %v", tt.s, got, tt.want) 35 | } 36 | }) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /snippets/how-to-get-the-sha256-checksum-of-a-string/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: db63511ab5e10dfc0709b6d1b65f383e3e4acc41b914debab9f9aad4be18c4a5 2 | playground_url: https://play.golang.org/p/lrqnEh3CGEb 3 | issue_id: 15 4 | -------------------------------------------------------------------------------- /snippets/how-to-include-the-filename-and-the-line-number-in-a-logger-output/main_test.go: -------------------------------------------------------------------------------- 1 | // Logging: How to include the filename and the line number in a logger output 2 | package main 3 | 4 | import ( 5 | "log" 6 | "os" 7 | ) 8 | 9 | func Example() { 10 | // You can configure the output format of a logger using 11 | // flags https://golang.org/pkg/log/#pkg-constants 12 | // Use log.LshortfileIf to print the filename without 13 | // the full path and the line number or 14 | // Use log.Llongfile to print the filename with 15 | // the full path and the line number 16 | // The log.Llongfile example is not included below 17 | // because playground use different path each time 18 | log.SetOutput(os.Stdout) 19 | log.SetFlags(log.Lshortfile) 20 | log.Println("Hello world") 21 | // Output: 22 | // prog.go:20: Hello world 23 | } 24 | -------------------------------------------------------------------------------- /snippets/how-to-include-the-filename-and-the-line-number-in-a-logger-output/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: b7dec07eed0f44c250d3dec8e7f3d4fbc18a1a9c63c7ba69628095aa26286103 2 | playground_url: https://play.golang.org/p/evhXCtHMF0m 3 | issue_id: 68 4 | -------------------------------------------------------------------------------- /snippets/how-to-measure-the-execution-time-of-a-function/main_test.go: -------------------------------------------------------------------------------- 1 | // Time: How to measure the execution time of a function 2 | // 3 | // This example demonstrates simple execution time calculation 4 | // If you need a detailed report on a function's performance 5 | // you should use Go benchmark functions 6 | // https://golang.org/pkg/testing/#hdr-Benchmarks 7 | // https://dave.cheney.net/2013/06/30/how-to-write-benchmarks-in-go 8 | package main 9 | 10 | import ( 11 | "fmt" 12 | "time" 13 | ) 14 | 15 | func f() { 16 | // first we calculate the exact time the function 17 | // started the execution 18 | start := time.Now() 19 | // Then we calculate the execution time duration 20 | // inside a deferred function, since it will be execute after f() returns 21 | defer func(start time.Time) { 22 | dur := time.Since(start) 23 | fmt.Printf("f() took %0.0f to execute", dur.Seconds()) 24 | }(start) 25 | // pause the execution for 2 seconds 26 | time.Sleep(2 * time.Second) 27 | } 28 | 29 | func Example() { 30 | f() 31 | // Output: 32 | // f() took 2 to execute 33 | } 34 | -------------------------------------------------------------------------------- /snippets/how-to-measure-the-execution-time-of-a-function/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 0091a97e2428f1e1bc2f80a20375a47ec5305ffaad7629b499bb0ba87f647486 2 | playground_url: https://play.golang.org/p/hSlDH_przPq 3 | issue_id: 48 4 | -------------------------------------------------------------------------------- /snippets/how-to-parse-comments-from-go-code/main_test.go: -------------------------------------------------------------------------------- 1 | // Parser: How to parse comments from Go Code 2 | // 3 | // Comments from Go code can be parsed using 4 | // go/parser package 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | "go/parser" 10 | "go/token" 11 | ) 12 | 13 | func Example() { 14 | src := ` 15 | // Calculator package provides methods 16 | // for basic int calculation 17 | package calculator 18 | 19 | // Import of fmt package 20 | import "fmt" 21 | 22 | // Add adds two integers 23 | func Add(a, b int) int { 24 | // calculate the result 25 | result := a + b 26 | // return the result 27 | return result 28 | } 29 | ` 30 | fs := token.NewFileSet() 31 | f, err := parser.ParseFile(fs, "", src, parser.ParseComments) 32 | if err != nil { 33 | fmt.Println(err) 34 | return 35 | } 36 | 37 | for _, c := range f.Comments { 38 | fmt.Println(c.Text()) 39 | } 40 | // Output: 41 | // Calculator package provides methods 42 | // for basic int calculation 43 | // 44 | // Import of fmt package 45 | // 46 | // Add adds two integers 47 | // 48 | // calculate the result 49 | // 50 | // return the result 51 | } 52 | -------------------------------------------------------------------------------- /snippets/how-to-parse-comments-from-go-code/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 1c54996353d47e306a085b3c72f044ed91f332fc8c0c50d5d6f9e75cb0a8a03f 2 | playground_url: https://play.golang.org/p/91vgF5JvyWm 3 | issue_id: 16 4 | -------------------------------------------------------------------------------- /snippets/how-to-pretty-print-json/main_test.go: -------------------------------------------------------------------------------- 1 | // Strings: How to pretty print JSON 2 | package main 3 | 4 | import ( 5 | "encoding/json" 6 | "fmt" 7 | ) 8 | 9 | type Student struct { 10 | Name string 11 | Age string 12 | Lessons []string 13 | } 14 | 15 | func Example() { 16 | s := Student{ 17 | Name: "John", 18 | Age: "17", 19 | Lessons: []string{ 20 | "Mathematics", 21 | "Computer science", 22 | "Philosophy", 23 | }, 24 | } 25 | 26 | // By using json.Marshal the output will be one line json string 27 | // which is difficult to read or debug 28 | jsonBytes, err := json.Marshal(s) 29 | if err != nil { 30 | fmt.Println(err) 31 | } 32 | fmt.Printf("\nUgly print:\n%s\n", jsonBytes) 33 | 34 | // The easiest way to achieve a human readable and pretty print 35 | // is to use the json.MarshalIndent 36 | jsonBytes, err = json.MarshalIndent(s, "", "\t") 37 | if err != nil { 38 | fmt.Println(err) 39 | } 40 | fmt.Printf("\nPretty print:\n%s\n", jsonBytes) 41 | // Output: 42 | // 43 | // Ugly print: 44 | // {"Name":"John","Age":"17","Lessons":["Mathematics","Computer science","Philosophy"]} 45 | // 46 | // Pretty print: 47 | // { 48 | // "Name": "John", 49 | // "Age": "17", 50 | // "Lessons": [ 51 | // "Mathematics", 52 | // "Computer science", 53 | // "Philosophy" 54 | // ] 55 | // } 56 | } 57 | -------------------------------------------------------------------------------- /snippets/how-to-pretty-print-json/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 34f13b1fd02972aaff97964ba61854cda53280b2ae0cf3a6b48d1f290cb0604c 2 | playground_url: https://play.golang.org/p/F81QBUjpigF 3 | issue_id: 17 4 | -------------------------------------------------------------------------------- /snippets/how-to-print-a-raw-http-response/main_test.go: -------------------------------------------------------------------------------- 1 | // HTTP: How to print a raw HTTP response 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "log" 7 | "net/http" 8 | "net/http/httptest" 9 | "net/http/httputil" 10 | ) 11 | 12 | func Example() { 13 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 14 | w.Header().Set("Date", "Wed, 01 Jan 2020 00:00:00 GMT") 15 | w.WriteHeader(http.StatusOK) 16 | w.Write([]byte("hello world")) 17 | })) 18 | defer ts.Close() 19 | 20 | resp, err := http.Get(ts.URL) 21 | if err != nil { 22 | fmt.Println(err) 23 | } 24 | defer resp.Body.Close() 25 | 26 | // DumpResponse returns wire representation 27 | // of the http response 28 | dump, err := httputil.DumpResponse(resp, true) 29 | if err != nil { 30 | log.Fatal(err) 31 | } 32 | // %q is used here to make the testable example work 33 | // use %s to print in multiple lines: 34 | // HTTP/1.1 200 OK 35 | // Content-Length: 11 36 | // Content-Type: text/plain; charset=utf-8 37 | // Date: Wed, 01 Jan 2020 00:00:00 GMT 38 | // 39 | // hello world 40 | fmt.Printf("%q", dump) 41 | // Output: 42 | // "HTTP/1.1 200 OK\r\nContent-Length: 11\r\nContent-Type: text/plain; charset=utf-8\r\nDate: Wed, 01 Jan 2020 00:00:00 GMT\r\n\r\nhello world" 43 | } 44 | -------------------------------------------------------------------------------- /snippets/how-to-print-a-raw-http-response/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 6a8b61deac07ab9a316bbb154dcf19a17d5a551ba074210d869f980f4b9ff21e 2 | playground_url: https://play.golang.org/p/T9qCD1vdAbI 3 | issue_id: 30 4 | -------------------------------------------------------------------------------- /snippets/how-to-print-go-version/main_test.go: -------------------------------------------------------------------------------- 1 | // Runtime: How to print Go version 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "runtime" 7 | ) 8 | 9 | func Example() { 10 | fmt.Printf("Go version: %s\n", runtime.Version()) 11 | // Output: 12 | // Go version: go1.14.2 13 | } 14 | -------------------------------------------------------------------------------- /snippets/how-to-print-go-version/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: dc57b277387897739906e5194913f3e943285a264c43271bb26bc847d98b98a3 2 | playground_url: https://play.golang.org/p/fTkteNt6GD_w 3 | issue_id: 18 4 | -------------------------------------------------------------------------------- /snippets/how-to-print-information-about-the-operating-system-architecture-and-pointer-size/main_test.go: -------------------------------------------------------------------------------- 1 | // Runtime: How to print information about the operating system, architecture and pointer size 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "runtime" 7 | "unsafe" 8 | ) 9 | 10 | func Example() { 11 | fmt.Printf("running program's operating system target: %s\n", runtime.GOOS) 12 | fmt.Printf("running program's architecture target: %s\n", runtime.GOARCH) 13 | var ptr uintptr 14 | ptrSize := int(unsafe.Sizeof(ptr)) 15 | fmt.Printf("pointer size: %d\n", ptrSize) 16 | // Output: 17 | // running program's operating system target: linux 18 | // running program's architecture target: amd64 19 | // pointer size: 8 20 | } 21 | -------------------------------------------------------------------------------- /snippets/how-to-print-information-about-the-operating-system-architecture-and-pointer-size/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 095fd7875cd9326f1ea33d41375d0966cdd89840453b48df03d34e1bc1fef8f4 2 | playground_url: https://play.golang.org/p/FCD9wEI2qIX 3 | issue_id: 27 4 | -------------------------------------------------------------------------------- /snippets/how-to-print-the-binary-representation-of-an-integer/main_test.go: -------------------------------------------------------------------------------- 1 | // Other: How to print the binary representation of an integer 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | func Example() { 9 | // The %b verb print the binary representation of an integer 10 | for x := 0; x < 16; x++ { 11 | fmt.Printf("%b\n", x) 12 | } 13 | // If you want the output to have the same length, 8 bits for example 14 | // use the %08b notation which means: 15 | // print binary, use 8 digits for the output, pad with leading zeros 16 | fmt.Println("fixed length of 8 digits:") 17 | for x := 0; x < 16; x++ { 18 | fmt.Printf("%08b\n", x) 19 | } 20 | // Output: 21 | // 0 22 | // 1 23 | // 10 24 | // 11 25 | // 100 26 | // 101 27 | // 110 28 | // 111 29 | // 1000 30 | // 1001 31 | // 1010 32 | // 1011 33 | // 1100 34 | // 1101 35 | // 1110 36 | // 1111 37 | // fixed length of 8 digits: 38 | // 00000000 39 | // 00000001 40 | // 00000010 41 | // 00000011 42 | // 00000100 43 | // 00000101 44 | // 00000110 45 | // 00000111 46 | // 00001000 47 | // 00001001 48 | // 00001010 49 | // 00001011 50 | // 00001100 51 | // 00001101 52 | // 00001110 53 | // 00001111 54 | } 55 | -------------------------------------------------------------------------------- /snippets/how-to-print-the-binary-representation-of-an-integer/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 293b03947aba72fd1e94ca99e92883d2c26f3377fca873f4b8669a4547c85c39 2 | playground_url: https://play.golang.org/p/ERtcvW-oUtx 3 | issue_id: 40 4 | -------------------------------------------------------------------------------- /snippets/how-to-print-the-same-variable-multiple-times-using-printf/main_test.go: -------------------------------------------------------------------------------- 1 | // Other: How to print the same variable multiple times using printf 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | func Example() { 9 | // You can print multiple times the same variable using argument indexes 10 | // The notation [n] before the verb, means use the nth argument after the format. 11 | // The above applies to Printf, Sprintf, and Fprintf 12 | fmt.Printf("%[1]d %[1]d\n", 5) 13 | fmt.Printf("%[2]d %[2]d %[1]d %[1]d\n", 5, 6) 14 | // Output: 15 | // 5 5 16 | // 6 6 5 5 17 | } 18 | -------------------------------------------------------------------------------- /snippets/how-to-print-the-same-variable-multiple-times-using-printf/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 4deabae791bf52092b1bf927e5cc151b5181f95930aadb1360278b0b83e18302 2 | playground_url: https://play.golang.org/p/Mz67TioNjAq 3 | issue_id: 41 4 | -------------------------------------------------------------------------------- /snippets/how-to-read-an-http-response-status-code/main_test.go: -------------------------------------------------------------------------------- 1 | // HTTP: How to read an HTTP response status code 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "net/http" 7 | "net/http/httptest" 8 | ) 9 | 10 | func Example() { 11 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 12 | w.WriteHeader(http.StatusOK) 13 | w.Write([]byte("hello world")) 14 | })) 15 | defer ts.Close() 16 | 17 | resp, err := http.Get(ts.URL) 18 | if err != nil { 19 | fmt.Println(err) 20 | } 21 | defer resp.Body.Close() 22 | 23 | fmt.Printf("%s\n", resp.Status) 24 | fmt.Printf("%d\n", resp.StatusCode) 25 | // Output: 26 | // 200 OK 27 | // 200 28 | } 29 | -------------------------------------------------------------------------------- /snippets/how-to-read-an-http-response-status-code/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: bd1c0ce086a725a9068b5518018f93f16e1717047a2d15772dfa2df0ea081093 2 | playground_url: https://play.golang.org/p/3HdEMGzECR7 3 | issue_id: 31 4 | -------------------------------------------------------------------------------- /snippets/how-to-remove-duplicate-elements-from-a-slice/main_test.go: -------------------------------------------------------------------------------- 1 | // Slices: How to remove duplicate elements from a slice 2 | package main 3 | 4 | import ( 5 | "reflect" 6 | "testing" 7 | ) 8 | 9 | func DeduplicateSlice(s []int) []int { 10 | if len(s) < 2 { 11 | return s 12 | } 13 | 14 | seen := make(map[int]struct{}) 15 | 16 | j := 0 17 | for k := range s { 18 | if _, ok := seen[s[k]]; ok { 19 | continue 20 | } 21 | seen[s[k]] = struct{}{} 22 | s[j] = s[k] 23 | j++ 24 | } 25 | 26 | return s[:j] 27 | } 28 | 29 | func TestDeduplicateSlice(t *testing.T) { 30 | tests := []struct { 31 | name string 32 | s []int 33 | want []int 34 | }{ 35 | { 36 | name: "nil", 37 | s: nil, 38 | want: nil, 39 | }, 40 | { 41 | name: "empty", 42 | s: []int{}, 43 | want: []int{}, 44 | }, 45 | { 46 | name: "one element", 47 | s: []int{1}, 48 | want: []int{1}, 49 | }, 50 | { 51 | name: "multiple elements", 52 | s: []int{1, 2, 3, 3, 2, 5, 3}, 53 | want: []int{1, 2, 3, 5}, 54 | }, 55 | } 56 | for _, tt := range tests { 57 | t.Run(tt.name, func(t *testing.T) { 58 | if got := DeduplicateSlice(tt.s); !reflect.DeepEqual(got, tt.want) { 59 | t.Errorf("DeduplicateSlice(%v) = %v, want %v", tt.s, got, tt.want) 60 | } 61 | }) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /snippets/how-to-remove-duplicate-elements-from-a-slice/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: d28372cf9cd5a1d8838c69efc322f8110563acac8ef4c2252a69f8df67414218 2 | playground_url: https://play.golang.org/p/iil-A7x_Win 3 | issue_id: 19 4 | -------------------------------------------------------------------------------- /snippets/how-to-reverse-a-slice/main_test.go: -------------------------------------------------------------------------------- 1 | // Slices: How to reverse a slice 2 | package main 3 | 4 | import ( 5 | "reflect" 6 | "testing" 7 | ) 8 | 9 | func ReverseSlice(s []int) []int { 10 | if len(s) < 2 { 11 | return s 12 | } 13 | 14 | for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { 15 | s[i], s[j] = s[j], s[i] 16 | } 17 | 18 | return s 19 | } 20 | 21 | func TestReverseSlice(t *testing.T) { 22 | tests := []struct { 23 | name string 24 | s []int 25 | want []int 26 | }{ 27 | { 28 | name: "nil", 29 | s: nil, 30 | want: nil, 31 | }, 32 | { 33 | name: "empty", 34 | s: []int{}, 35 | want: []int{}, 36 | }, 37 | { 38 | name: "one element", 39 | s: []int{1}, 40 | want: []int{1}, 41 | }, 42 | { 43 | name: "odd elements", 44 | s: []int{1, 2, 3, 4}, 45 | want: []int{4, 3, 2, 1}, 46 | }, 47 | { 48 | name: "even elements", 49 | s: []int{1, 2, 3, 4, 5}, 50 | want: []int{5, 4, 3, 2, 1}, 51 | }, 52 | } 53 | for _, tt := range tests { 54 | t.Run(tt.name, func(t *testing.T) { 55 | if got := ReverseSlice(tt.s); !reflect.DeepEqual(got, tt.want) { 56 | t.Errorf("ReverseSlice(%v) = %v, want %v", tt.s, got, tt.want) 57 | } 58 | }) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /snippets/how-to-reverse-a-slice/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 1d2ff3942664a5be745e03c392a54280b8b036dd0bff9c9b35a120eda2069be3 2 | playground_url: https://play.golang.org/p/v78uxond44a 3 | issue_id: 20 4 | -------------------------------------------------------------------------------- /snippets/how-to-reverse-a-string/main_test.go: -------------------------------------------------------------------------------- 1 | // Strings: How to reverse a string 2 | package main 3 | 4 | import "testing" 5 | 6 | func ReverseString(s string) string { 7 | r := []rune(s) 8 | for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { 9 | r[i], r[j] = r[j], r[i] 10 | } 11 | 12 | return string(r) 13 | } 14 | 15 | func TestReverseString(t *testing.T) { 16 | tests := []struct { 17 | name string 18 | s string 19 | want string 20 | }{ 21 | { 22 | name: "empty", 23 | s: "", 24 | want: "", 25 | }, 26 | { 27 | name: "non empty ascii", 28 | s: "abcd", 29 | want: "dcba", 30 | }, 31 | { 32 | name: "non empty utf8", 33 | s: "καλημέρα", 34 | want: "αρέμηλακ", 35 | }, 36 | } 37 | for _, tt := range tests { 38 | t.Run(tt.name, func(t *testing.T) { 39 | if got := ReverseString(tt.s); got != tt.want { 40 | t.Errorf("ReverseString(%q) = %v, want %v", tt.s, got, tt.want) 41 | } 42 | }) 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /snippets/how-to-reverse-a-string/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 0b6dddeeb4f5165ebe1a6414d76da0e6a78d71d2a40e60caa3828e844a039d08 2 | playground_url: https://play.golang.org/p/8jAL16Z9jc9 3 | issue_id: 50 4 | -------------------------------------------------------------------------------- /snippets/how-to-shuffle-a-slice/main_test.go: -------------------------------------------------------------------------------- 1 | // Slices: How to shuffle a slice 2 | package main 3 | 4 | import ( 5 | "math/rand" 6 | "reflect" 7 | "sort" 8 | "testing" 9 | "time" 10 | ) 11 | 12 | func ShuffleSlice(a []int) []int { 13 | r := rand.New(rand.NewSource(time.Now().UnixNano())) 14 | r.Shuffle(len(a), func(i, j int) { 15 | a[i], a[j] = a[j], a[i] 16 | }) 17 | 18 | return a 19 | } 20 | 21 | func TestShuffleSlice(t *testing.T) { 22 | // start with a sorted slice 23 | s := []int{1, 2, 3, 4, 5} 24 | 25 | // make a copy of the s slice and keep it as reference 26 | // for later comparison since the ShuffleSlice is an in place operation 27 | // and it will change s slice 28 | // See https://github.com/go101/go101/wiki/How-to-perfectly-clone-a-slice 29 | original := append(s[:0:0], s...) 30 | 31 | // shuffle the slice and check that it is different from the original 32 | shuffled := ShuffleSlice(s) 33 | if reflect.DeepEqual(shuffled, original) { 34 | t.Errorf("Shuffled slice should be different from the original") 35 | } 36 | 37 | // Sort the shuffled slice in order to ensure that its elements are the same with the original 38 | sort.Slice(shuffled, func(i, j int) bool { 39 | return shuffled[i] < shuffled[j] 40 | }) 41 | if !reflect.DeepEqual(shuffled, original) { 42 | t.Errorf("Sorted shuffled slice should be the same with the original") 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /snippets/how-to-shuffle-a-slice/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 7a883bed30f5d08e865ddf346dc7f9ee22360b29a6e36e8bbbe1c7ddc9a5b7c9 2 | playground_url: https://play.golang.org/p/-pN_TSFJzP_R 3 | issue_id: 21 4 | -------------------------------------------------------------------------------- /snippets/how-to-split-a-slice-in-chunks/main_test.go: -------------------------------------------------------------------------------- 1 | // Slices: How to split a slice in chunks 2 | package main 3 | 4 | import ( 5 | "errors" 6 | "fmt" 7 | "reflect" 8 | "testing" 9 | ) 10 | 11 | func SplitSliceInChunks(a []int, chuckSize int) ([][]int, error) { 12 | if chuckSize < 1 { 13 | return nil, errors.New("chuckSize must be greater that zero") 14 | } 15 | chunks := make([][]int, 0, (len(a)+chuckSize-1)/chuckSize) 16 | 17 | for chuckSize < len(a) { 18 | a, chunks = a[chuckSize:], append(chunks, a[0:chuckSize:chuckSize]) 19 | } 20 | chunks = append(chunks, a) 21 | return chunks, nil 22 | } 23 | 24 | func TestSplitSliceInChunks(t *testing.T) { 25 | tests := []struct { 26 | name string 27 | a []int 28 | chuckSize int 29 | want [][]int 30 | wantErr bool 31 | }{ 32 | { 33 | name: "", 34 | a: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 35 | chuckSize: 1, 36 | want: [][]int{ 37 | {0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, 38 | }, 39 | wantErr: false, 40 | }, 41 | { 42 | name: "", 43 | a: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 44 | chuckSize: 10, 45 | want: [][]int{ 46 | {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 47 | }, 48 | wantErr: false, 49 | }, 50 | { 51 | name: "", 52 | a: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 53 | chuckSize: 3, 54 | want: [][]int{ 55 | {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9}, 56 | }, 57 | wantErr: false, 58 | }, 59 | { 60 | name: "", 61 | a: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 62 | chuckSize: 5, 63 | want: [][]int{ 64 | {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, 65 | }, 66 | wantErr: false, 67 | }, 68 | } 69 | for _, tt := range tests { 70 | t.Run(tt.name, func(t *testing.T) { 71 | got, err := SplitSliceInChunks(tt.a, tt.chuckSize) 72 | if (err != nil) != tt.wantErr { 73 | t.Errorf("SplitSliceInChunks(%v, %d) error = %v, wantErr %v", tt.a, tt.chuckSize, err, tt.wantErr) 74 | return 75 | } 76 | if !reflect.DeepEqual(got, tt.want) { 77 | t.Errorf("SplitSliceInChunks(%v, %d) got = %v, want %v", tt.a, tt.chuckSize, got, tt.want) 78 | } 79 | }) 80 | } 81 | } 82 | 83 | func ExampleSplitSliceInChunks() { 84 | a := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} 85 | chunks, err := SplitSliceInChunks(a, 4) 86 | if err != nil { 87 | fmt.Println(err) 88 | } 89 | fmt.Printf("%v", chunks) 90 | // Output: 91 | // [[0 1 2 3] [4 5 6 7] [8 9]] 92 | } 93 | -------------------------------------------------------------------------------- /snippets/how-to-split-a-slice-in-chunks/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 709e11c1ae12e8e43cba1b08790ccbfbb78c327633a6d579cff6c7f4ab819249 2 | playground_url: https://play.golang.org/p/n3_iT81aPfP 3 | issue_id: 69 4 | -------------------------------------------------------------------------------- /snippets/how-to-test-a-function-that-panics/main_test.go: -------------------------------------------------------------------------------- 1 | // Testing: How to test a function that panics 2 | package main 3 | 4 | import "testing" 5 | 6 | func f(shouldPanic bool) string { 7 | if shouldPanic { 8 | panic("function panicked") 9 | } 10 | return "function didn't panic" 11 | } 12 | 13 | func Test_f(t *testing.T) { 14 | t.Run("panics", func(t *testing.T) { 15 | // If the function panics, recover() will 16 | // return a non nil value. 17 | defer func() { 18 | if r := recover(); r == nil { 19 | t.Errorf("function should panic") 20 | } 21 | }() 22 | 23 | f(true) 24 | }) 25 | 26 | t.Run("does not panic", func(t *testing.T) { 27 | shouldPanic := false 28 | want := "function didn't panic" 29 | if got := f(shouldPanic); got != want { 30 | t.Errorf("f(%v) = %v, want %v", shouldPanic, got, want) 31 | } 32 | }) 33 | 34 | } 35 | -------------------------------------------------------------------------------- /snippets/how-to-test-a-function-that-panics/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 8c628ca6c9678b6d6130eae426e0c8f99aff59f06e815a621d39e5c32c72be2a 2 | playground_url: https://play.golang.org/p/EFekGRTM7Dg 3 | issue_id: 22 4 | -------------------------------------------------------------------------------- /snippets/what-is-the-maximum-value-of-numeric-types/main_test.go: -------------------------------------------------------------------------------- 1 | // Numbers: What is the maximum value of numeric types 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "math" 7 | ) 8 | 9 | func Example() { 10 | fmt.Println("Max int8:", math.MaxInt8) 11 | fmt.Println("Max int16:", math.MaxInt16) 12 | fmt.Println("Max int32:", math.MaxInt32) 13 | fmt.Println("Max int64:", math.MaxInt64) 14 | fmt.Println("Max uint8:", math.MaxUint8) 15 | fmt.Println("Max uint16:", math.MaxUint16) 16 | fmt.Println("Max uint32:", math.MaxUint32) 17 | // See https://github.com/golang/go/issues/19621 18 | fmt.Println("Max uint64:", uint64(math.MaxUint64)) 19 | fmt.Println("Max float32:", math.MaxFloat32) 20 | fmt.Println("Max float64:", math.MaxFloat64) 21 | // Output: 22 | // Max int8: 127 23 | // Max int16: 32767 24 | // Max int32: 2147483647 25 | // Max int64: 9223372036854775807 26 | // Max uint8: 255 27 | // Max uint16: 65535 28 | // Max uint32: 4294967295 29 | // Max uint64: 18446744073709551615 30 | // Max float32: 3.4028234663852886e+38 31 | // Max float64: 1.7976931348623157e+308 32 | } 33 | -------------------------------------------------------------------------------- /snippets/what-is-the-maximum-value-of-numeric-types/metadata.yml: -------------------------------------------------------------------------------- 1 | hash: 6fe4a318a40cd20627dc5e484742860358a340bbda0fbabe35607cd0f19aa41e 2 | playground_url: https://play.golang.org/p/qeElniC-Nin 3 | issue_id: 23 4 | -------------------------------------------------------------------------------- /tools/templates/html_index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | GopherSnippets - Go code snippets 7 | 8 | 9 |
10 |
11 |
12 |
13 |

GopherSnippetsStar

14 |

Code snippets with tests and testable examples for the Go programming language

15 | {{ $repo := .Repo}} 16 |
17 | {{range $category := .Categories}} 18 |
{{$category}}
19 | {{- range $snippet := index $.Snippets $category }} 20 |
{{$snippet.Title}}
21 | {{- end -}} 22 | {{end}} 23 |
24 |

25 | by psampaz - source code 26 |

27 |
28 |
29 |
30 |
31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /tools/templates/html_page.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | {{.Snippet.Title}} - GopherSnippets.com 8 | 9 | 10 |
11 |
12 |
13 |
14 |

GopherSnippetsStar

15 |

Code snippets with tests and testable examples for the Go programming language

16 |

{{.Snippet.Title}}

17 | Snippets Index - Run code on Go playground - 18 | Edit 20 |

21 | {{.Snippet.GetHighlightedCode}} 22 |

23 |

24 | by psampaz - 25 | source code - comment below or here 27 |

28 | 35 |
36 |
37 |
38 |
39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /tools/templates/issue.tmpl: -------------------------------------------------------------------------------- 1 | Comments for [{{.Title}}](http://gophersnippets.com/{{.DirectoryName}}) 2 | -------------------------------------------------------------------------------- /tools/templates/readme.md: -------------------------------------------------------------------------------- 1 | **[gophersnippets](https://gophersnippets.com)** is a collection of code snippets with tests and testable examples for the Go programming language. 2 | 3 | Each snippet: 4 | - is small and shows how to achieve something specific with Go 5 | - contains at least one test or testable example 6 | - runs on [Go playground](https://play.golang.org/) since it now supports tests and testable examples 7 | 8 | ## Snippets 9 | {{ $repo := .Repo}} 10 | {{range $category := .Categories}} 11 | ### {{$category}} 12 | {{- range $snippet := index $.Snippets $category }} 13 | - [{{$snippet.Title}}](https://gophersnippets.com/{{$snippet.DirectoryName}}) 14 | {{- end -}} 15 | {{end}} 16 | 17 | ## Comments 18 | 19 | https://gophersnippets.com uses Github issues for comments, powered by https://utteranc.es/. You can add comments directly on the corresponding Github issue or use the comment form under each code section. 20 | 21 | ## Contributing 22 | 23 | You are welcome to contribute testable Go code snippets. 24 | 25 | Please read the following before submitting a PR: 26 | - https://blog.golang.org/examples 27 | - https://blog.golang.org/playground 28 | - https://github.com/golang/go/wiki/TableDrivenTests 29 | 30 | ### Guidelines: 31 | 32 | - Include only one code snippet per PR 33 | - The snippet should be small and solve one problem only 34 | - Include comments when necessary 35 | - When you submit a PR the following checks will run automatically: 36 | - code includes at least 1 test or testable example 37 | - code runs successfully on play.golang.org 38 | - code passes go vet 39 | - code includes a category and a title in the first line of the code (Category: Title) 40 | ```go 41 | // Strings: How to reverse a string 42 | // package main 43 | ``` 44 | or includes a category and title in the first line of the code, an empty comment line and then a description 45 | ```go 46 | // Strings: How to reverse a string 47 | // 48 | // Description 49 | // package main 50 | ``` 51 | - code should be included in **one file only**, named **main_test.go**. This is necessary in order to test and run snippets locally 52 | - folder should match the slug version of the title: 53 | 54 | if the title is **How to reverse a string**, 55 | 56 | the folder should be **snippets/how-to-reverse-a-string** 57 | 58 | and the full path should be **snippets/how-to-reverse-a-string/main_test.go** 59 | - Do no edit anything inside docs folder. It is generated automatically on succesful merge 60 | - Do no edit README.md. It is generated automatically on succesful merge. Edit https://github.com/psampaz/gophersnippets/edit/contributing/tools/templates/readme.md instead. 61 | 62 | ## License 63 | Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. 64 | --------------------------------------------------------------------------------