├── LICENSE ├── README.md ├── _docs ├── presentations │ ├── 1.pdf │ ├── 2+1.pdf │ ├── 2.pdf │ ├── 3.pdf │ ├── DevFest_go_workshop.pdf │ ├── GopherconRU2019_tasks.pdf │ └── prepare_env_guide.pdf └── tasks │ └── tasks.org ├── _stickers ├── sticker.png └── sticker_square.png └── kfugo ├── README.md ├── cmd ├── hello_world │ └── main.go └── json_encode │ └── main.go └── scratch ├── bignum └── main.go ├── files └── main.go ├── go_ast └── main.go ├── parse_number └── main.go ├── regexp └── main.go ├── sort └── main.go └── strings └── main.go /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Iskander Sharipov / Quasilyte 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [Go](https://golang.org/) contributing [русскоязычного сообщества](http://slack.golang-ru.com/) 2 | 3 | > **Notice:** this repository is intended to make contributing to Go easier 4 | > for Russian speaking members of the community. 5 | > There are plenty of materials on that topic in other languages, 6 | > hence no translation for this very repository is provided. 7 | 8 | Для чего существует данный репозиторий: 9 | * Объединять контрибьюторов из России 10 | * Собирать обучающий материал и предоставлять переводы на русский, переиспользование и передача знаний 11 | * [Go contribution workshop](https://blog.golang.org/contributor-workshop)'ы 12 | 13 | ## Шаг 1 - присоединяйтесь 14 | 15 | 1. Основная часть русскоязычного сообщества общается в [golang-ru слаке](http://slack.golang-ru.com/). 16 | 2. Внутри этого workspace есть канал `#gocontributing`. 17 | 18 | ## Шаг 2 - выбирайте свой путь 19 | 20 | 1. Начинающие: ни разу не отправлял изменения в проект Go, хочу начать. 21 | 2. Продолжающие: сделал одно или несколько изменений в Go, что дальше? 22 | 3. Менторы: планирую провести contribution workshop. 23 | 24 | TODO: предоставить ссылки для каждого направления. 25 | 26 | ## Шаг 3 - помогайте в развитии инициативы 27 | 28 | * Делитесь полезными ссылками 29 | * Помогайте переводить и поддерживать в актуальном состоянии релевантные документы 30 | * Рассказывайте об этом на митапах, организуйте contribution workshop'ы 31 | * Участвуйте в совместном планировании, делитесь идеями, помогайте другим, если можете 32 | 33 | ## Навигация 34 | 35 | TODO: добавить меню для навигации по содержимому репозитория. 36 | -------------------------------------------------------------------------------- /_docs/presentations/1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quasilyte/go-contributing-ru/deda4fd4f79ce3fd3136bd8804f3a5267e167016/_docs/presentations/1.pdf -------------------------------------------------------------------------------- /_docs/presentations/2+1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quasilyte/go-contributing-ru/deda4fd4f79ce3fd3136bd8804f3a5267e167016/_docs/presentations/2+1.pdf -------------------------------------------------------------------------------- /_docs/presentations/2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quasilyte/go-contributing-ru/deda4fd4f79ce3fd3136bd8804f3a5267e167016/_docs/presentations/2.pdf -------------------------------------------------------------------------------- /_docs/presentations/3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quasilyte/go-contributing-ru/deda4fd4f79ce3fd3136bd8804f3a5267e167016/_docs/presentations/3.pdf -------------------------------------------------------------------------------- /_docs/presentations/DevFest_go_workshop.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quasilyte/go-contributing-ru/deda4fd4f79ce3fd3136bd8804f3a5267e167016/_docs/presentations/DevFest_go_workshop.pdf -------------------------------------------------------------------------------- /_docs/presentations/GopherconRU2019_tasks.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quasilyte/go-contributing-ru/deda4fd4f79ce3fd3136bd8804f3a5267e167016/_docs/presentations/GopherconRU2019_tasks.pdf -------------------------------------------------------------------------------- /_docs/presentations/prepare_env_guide.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quasilyte/go-contributing-ru/deda4fd4f79ce3fd3136bd8804f3a5267e167016/_docs/presentations/prepare_env_guide.pdf -------------------------------------------------------------------------------- /_docs/tasks/tasks.org: -------------------------------------------------------------------------------- 1 | KFU Go contributors workshop 2018. 2 | 3 | Формально, никакого специального списка задач не существует. 4 | С Go трекера можно попробовать решить любую задачу (есть нюансы). 5 | Ссылка на трекер: https://github.com/golang/go/issues. 6 | 7 | Лучше всего сначала рассматривать задачи, отмеченные "Help Wanted": 8 | https://github.com/golang/go/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+label%3A%22Help+Wanted%22. 9 | 10 | Распределённые задачи: 11 | 12 | | ID | Title | Assignees | 13 | |-------+---------------------------------------------------------------------+-----------| 14 | | 22369 | encoding/json: add the full path to the field in UnmarshalTypeError | Делюс | 15 | | 17858 | time: optimize time.Time.Sub and time.Since | Никита | 16 | | 21735 | cmd/compile: avoid slow versions of LEA instructions on x86 | Артём | 17 | 18 | То, что приведено в этом файле, является чем-то вроде "списком задач по умолчанию". 19 | 20 | | ID | Title | Difficulty | Kind | 21 | |-------+----------------------------------------------------------------------------------+------------+-------------| 22 | | 21779 | all: reduce golint errors on standard library | ★★ | refactoring | 23 | | 24352 | go: add more examples to go/* package documentation | ★★ | docs | 24 | | 23471 | x/perf/cmd/benchstat: tips or quickstart for newcomers | ★★ | docs | 25 | | 23386 | cmd/internal/obj/x86: FSAVE assembled as FNSAVE | ★★ | bugfix | 26 | | 20396 | encoding/xml: accepts invalid XML with multiple colons | ★★ | bugfix | 27 | | 19683 | cmd/compile: eliminate usages of global lineno | ★★ | refactoring | 28 | | 18581 | doc: fix where we forgot to target Windows users | ★★ | docs | 29 | | 19636 | encoding/base64: decoding is slow | ★★★ | performance | 30 | | 22095 | cmd/link: code cleanup | ★★★ | refactoring | 31 | | 21045 | cmd/go: do nothing with explicitly specified "_*" file | ★★★ | bugfix | 32 | | 20032 | cmd/vet: eliminate use of Perl in tests | ★★★ | re-write | 33 | | 19675 | cmd/vet: report uses of -0 in float32/64 context | ★★★ | improvement | 34 | | 18072 | cmd/asm/internal/asm: add encoding tests for all architectures | ★★★ | testing | 35 | | 24499 | image/jpeg: Decode is slow | ★★★★ | performance | 36 | | 22555 | cmd/go: cgo compilation fails when LDFLAGS refers to a @file | ★★★★ | feature | 37 | | 20235 | encoding/base64: integer overflow in (*Encoding).EncodedLen | ★★★★ | bugfix | 38 | | 22446 | cmd/link: doesn't propagate -I flags to the external linker | ★★★★ | bugfix | 39 | | 19042 | cmd/internal/obj: optimize wrapper method prologue for branch prediction | ★★★★ | improvement | 40 | | 19670 | x/tools/go/ssa: make opaqueType less annoying to use | ★★★★ | improvement | 41 | | 19013 | cmd/compile: add tool for understanding/debugging SSA rules | ★★★★ | feature | 42 | | 20906 | math/big: big.Int String conversion is slow | ★★★★★ | performance | 43 | | 20184 | cmd/compile: wasted bucket allocated for non-escaping map when hint is not small | ★★★★★ | improvement | 44 | | 19577 | test: errorcheck support for intraline errors | ★★★★★ | improvement | 45 | | 19490 | cmd/vet: reduce the amount of false positives for -shadow mode | ★★★★★ | improvement | 46 | | 18601 | net: poor performance of Dial & friends | ★★★★★ | performance | 47 | | 18269 | cmd/compile: remove stack check for leaf routines | ★★★★★ | improvement | 48 | | 17926 | cmd/compile: insertVarPhis is very slow | ★★★★★ | performance | 49 | 50 | Описания столбцов из таблицы выше: 51 | | Column | Description | 52 | |------------+---------------------------------------------------------------------------------------------------| 53 | | ID | Github issue ID. "https://github.com/golang/go/issues/$ID" формирует URL | 54 | | Title | Заголовок с github трекера. Иногда немного изменено в пользу информативности | 55 | | Diffuculty | Чем выше сложность, тем выше риск не успеть задачу в рамках курса (больше самостоятельной работы) | 56 | | Kind | Примерная классификация задачи | 57 | 58 | Задачи, которые не оформлены в трекере Go, но потенциально имеющие смысл: 59 | | Title | Difficulty | Kind | 60 | |------------------------------------------------------------------------------+------------+-------------| 61 | | cmd/internal/obj/x86: unexport as much internal types as possible | ★ | refactoring | 62 | | cmd/internal/obj/x86: fix lint errors in obj6_test.go | ★ | refactoring | 63 | | example/gotypes: more "Getting from A to B" | ★★ | docs | 64 | | example/gotypes: fix TODO/FIXME inside document | ★★ | docs | 65 | | fixedbugs/issue10607 fails on GOARCH=386 if there is no -lgcc (gcc-multilib) | ★★★ | improvement | 66 | | cmd/compile: document Phi order after "schedule" pass (see 20178) | ★★★ | docs | 67 | | cmd/asm/internal/asm: add more parser tests | ★★★ | testing | 68 | -------------------------------------------------------------------------------- /_stickers/sticker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quasilyte/go-contributing-ru/deda4fd4f79ce3fd3136bd8804f3a5267e167016/_stickers/sticker.png -------------------------------------------------------------------------------- /_stickers/sticker_square.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quasilyte/go-contributing-ru/deda4fd4f79ce3fd3136bd8804f3a5267e167016/_stickers/sticker_square.png -------------------------------------------------------------------------------- /kfugo/README.md: -------------------------------------------------------------------------------- 1 | # KFU [Go](https://golang.org/) курсы 2 | 3 | > Notice: this course is for Russian university and there is no english version. 4 | > In general though, all participants are welcome. 5 | 6 | Данный репозиторий содержит вспомогательный материал, на который 7 | время от времени делаются отсылки в лекционных презентациях. 8 | 9 | Сами презентации лежат здесь же, в каталоге [_docs/presentations](/_docs/presentations). 10 | 11 | Информацию о практических заданиях можно найти в каталоге [_docs/tasks](/_docs/tasks/tasks.org). 12 | 13 | [Таблицу результатов](#Трофеи) можно посмотреть в самом низу этого документа. 14 | 15 | > ВАЖНО: документацию по стандартным пакетам можно смотреть на [golang.org/pkg](https://golang.org/pkg/). 16 | > Её также можно поднять локально, с помощью `godoc -http=8080`, после этого документация 17 | > будет доступна по адресу `http://localhost:8080/`. 18 | 19 | ## План занятий 20 | 21 | 1. [Вводное занятие](/_docs/presentations/1.pdf). 22 | 2. [Первый коммит в go-review.googlesource](/_docs/presentations/2.pdf). 23 | 3. **Workshop** + [синтез двух лекций](/_docs/presentations/2+1.pdf) для новых студентов. 24 | 4. **Workshop** + [введение в профилирование и оптимизацию](/_docs/presentations/3.pdf). 25 | 5. Очное занятие отменено. 26 | 27 | **Workshop** - это интерактивный формат, когда люди могут работать над своими 28 | патчами в Go параллельно основному лекционному треку. 29 | 30 | Для всех новых студентов есть [доработанные слайды](/_docs/presentations/2+1.pdf) для быстрого вовлечения. 31 | 32 | Официальный Contribution Guide: 33 | - [Новая версия](https://tip.golang.org/doc/contribute.html) (рекомендуется) 34 | - [Текущая версия](https://golang.org/doc/contribute.html) 35 | 36 | **Обновление**: курс проходил с марта по май, затем был приостановлен из-за [code freeze](https://groups.google.com/forum/#!topic/golang-dev/a1YnheC_ku4). За это время участники успели выслать **17** патчей. 37 | 38 | ## Полезные ссылки 39 | 40 | [GolangShow](http://golangshow.com) - русскоязычный подкаст о Go. Крутые ведущие, интересные гости. 41 | 42 | [golang-ru Slack](http://slack.golang-ru.com) - русскоязычное Go сообщество. 43 | Там можно задавать вопросы, обсуждать Go, библиотеки под него и прочее. 44 | Для вопросов лучше всего подходит канал `#school` (при формулировке вопроса можно 45 | опираться на [How To Ask Questions The Smart Way](http://www.catb.org/esr/faqs/smart-questions.html)). 46 | Всем участникам следует соблюдать [кодекс норм поведения](https://golang.org/conduct). 47 | 48 | Google проводил [Contribution Workshop](https://blog.golang.org/contributor-workshop). 49 | Это мероприятие во многом является идейным вдохновителем для этих курсов (но по размаху 50 | их догнать невозможно). Кроме интересного описания самого события, в Go блоге, где 51 | опубликован этот доклад, есть ещё много других качественных постов. 52 | 53 | Есть хорошая презентация на английском: [How to contribute to Go](https://docs.google.com/presentation/d/1ap2fycBSgoo-jCswhK9lqgCIFroE1pYpsXC1ffYBCq4/edit#slide=id.p). 54 | Только оттуда стоит выбросить всё, что привязано к давно прошедшему gophercon. 55 | 56 | Видео доклада на тему "How to contribute to Go" на русском: 57 | https://www.youtube.com/watch?v=0a8u74Ul-hM&feature=youtu.be. 58 | 59 | [Go and fix me](https://www.goandfix.me/) - сервис, который отображает проблемы, найдённые линтерами в репозитории Go. 60 | Очень удобен для нахождения почвы для первых CL. (Временами недоступен, возможно проблемы с хостингом.) 61 | 62 | [goissues](https://goissues.org) кому-то может быть удобнее, чем сам github issue tracker. 63 | 64 | ## Ссылки, полезные для обучения 65 | 66 | Большинство ссылок легко найти в гугле по запросу "golang learning resources". 67 | Самое главное правило - всегда искать по слову `golang`, а не `go`. 68 | Ниже наиболее стоящие результаты с описаниями. 69 | 70 | [Resources for new Go programmers](https://dave.cheney.net/resources-for-new-go-programmers) - статья [Dave Cheney](https://dave.cheney.net/about), одного из ведущих разработчиков Go. 71 | 72 | [golang/go/wiki/Learn](https://github.com/golang/go/wiki/Learn) - много учебного материала. 73 | 74 | [Go tour](https://tour.golang.org) - интерактивный Go тур. Доступен на русском, но лучше 75 | проходить в оригинале. Этот вариант изучения классический, но может быть местами сложноват. 76 | 77 | [Go videos](https://github.com/hH39797J/golang-videos-ru) - собрание видеозаписей докладов про Go. 78 | 79 | [Go by example](https://gobyexample.com/) - примеры кода на Go с комментариями и описаниями. 80 | 81 | [Go webdev examples](https://gowebexamples.com/) - аналог Go by example, но с уклоном в веб разработку. 82 | 83 | ## Трофеи 84 | 85 | Таблица изменений, которые были посланы на go-review. 86 | 87 | | Ссылка на изменение | Автор | Статус | 88 | |---------------------|-------|--------| 89 | | https://golang.org/cl/105356 | bontequero / Делюс | merged | 90 | | https://golang.org/cl/105495 | bontequero / Делюс | merged | 91 | | https://golang.org/cl/105736 | bontequero / Делюс | merged | 92 | | https://golang.org/cl/107235 | bontequero / Делюс | merged | 93 | | https://golang.org/cl/108275 | tengufromsky / Никита | merged | 94 | | https://golang.org/cl/105556 | tengufromsky / Никита | merged | 95 | | https://golang.org/cl/107018 | tengufromsky / Никита | merged | 96 | | https://golang.org/cl/107056 | tengufromsky / Никита | merged | 97 | | https://golang.org/cl/105415 | fexolm / Артём | merged | 98 | | https://golang.org/cl/105395 | fexolm / Артём | merged | 99 | | https://golang.org/cl/105355 | fexolm / Артём | merged | 100 | | https://golang.org/cl/105375 | weeellz / Равиль | merged | 101 | | https://golang.org/cl/107135 | weeellz / Равиль | merged | 102 | | https://golang.org/cl/107115 | weeellz / Равиль | merged | 103 | | https://golang.org/cl/105416 | ludweeg / Эмиль | merged | 104 | | https://golang.org/cl/108659 | ludweeg / Эмиль | merged | 105 | | https://golang.org/cl/108815 | ludweeg / Эмиль | merged | 106 | 107 | Итого: 17. 108 | 109 | ---- 110 | 111 | kfu-go-2018 112 | kfu go 2018 113 | -------------------------------------------------------------------------------- /kfugo/cmd/hello_world/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func main() { 9 | xs := []string{"Hello", "World"} 10 | fmt.Println(strings.Join(xs, ", ")) 11 | } 12 | -------------------------------------------------------------------------------- /kfugo/cmd/json_encode/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "log" 7 | ) 8 | 9 | // Point описывает точку в двухмерном пространстве. 10 | type Point struct { 11 | X float64 12 | Y float64 13 | } 14 | 15 | func main() { 16 | a := Point{X: 1, Y: 2} 17 | 18 | data, err := json.Marshal(a) 19 | if err != nil { 20 | log.Fatal(err) 21 | } 22 | 23 | fmt.Printf("%v => %s\n", a, data) 24 | // Печатает: 25 | // {1 2} => {"X":1,"Y":2} 26 | } 27 | -------------------------------------------------------------------------------- /kfugo/scratch/bignum/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "fmt" // Formatted I/O with functions analogous to C's printf and scanf. 9 | "log" // Simple logging package. 10 | "math/big" // Arbitrary-precision arithmetic (big numbers). 11 | ) 12 | 13 | // Hint: ":=" declares and initializes, but "=" only assigns to already defined names. 14 | 15 | func main() { 16 | x := new(big.Int) // new returns *T, in this case, it's *big.Int 17 | y := &big.Int{} // It's also possible to use literal with "&" 18 | 19 | x, ok = x.SetString("999888777666555444333222111000", 10) 20 | if !ok { 21 | log.Fatal("failed to set value for x") 22 | } 23 | // Can use "_" to ignore certain return value. 24 | y, _ = y.SetString("1", 10) 25 | 26 | var result big.Int // Defines result variable. Initialized to zero value. 27 | result.Add(x, y) 28 | 29 | fmt.Printf("result=%s\n", result.String()) 30 | } 31 | -------------------------------------------------------------------------------- /kfugo/scratch/files/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "fmt" // Formatted I/O with functions analogous to C's printf and scanf. 9 | "io/ioutil" // Convenient functions for simple I/O tasks. 10 | "log" // Simple logging package. 11 | "os" // OS-dependent functions. 12 | ) 13 | 14 | // Hint: string can be converted to []byte using type conversion. 15 | 16 | func main() { 17 | // Type conversion from untyped literal to os.FileMode: 18 | permissions := os.FileMode(0666) 19 | filename := "my_file.txt" 20 | err := ioutil.WriteFile(filename, "123", permissions) 21 | if err != nil { 22 | log.Fatalf("write file: %v", err) 23 | } 24 | 25 | // Read file contents. 26 | data, err := ioutil.ReadFile(filename) 27 | if err != nil { 28 | log.Fatalf("read file: %v", err) 29 | } 30 | fmt.Printf("data: '%s'\n", data) 31 | 32 | if err := os.Remove(filename); err != nil { 33 | log.Fatalf("remove file: %v", err) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /kfugo/scratch/go_ast/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "fmt" // Formatted I/O with functions analogous to C's printf and scanf. 9 | "go/ast" // Go AST. Produced by parsing Go sources. 10 | "go/parser" // Go parser. 11 | "log" // Simple logging package. 12 | ) 13 | 14 | // Hint: there is no implicit boolean conversion. 15 | 16 | func main() { 17 | src := `int(x) + y * z` 18 | expr, err := parser.ParseExpr(src) 19 | if err != nil { 20 | log.Fatalf("parse expr: %v", err) 21 | } 22 | 23 | // Walk AST nodes. 24 | ast.Inspect(expr, func(node ast.Node) bool { 25 | if node != nil { 26 | begin := node.Pos() - 1 27 | end := node.End() - 1 28 | fmt.Printf("node=%T: `%s`\n", node, src[begin:end]) 29 | } 30 | return true 31 | }) 32 | 33 | err = ast.Print(nil, expr) // Print AST 34 | if !err { 35 | log.Fatalf("print AST: %v", err) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /kfugo/scratch/parse_number/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "log" // Simple logging package. 9 | "strconv" // Conversions to and from string representations. 10 | ) 11 | 12 | // Tip: explicit type conversion (cast) is needed to compare 13 | // two values of different types. 14 | 15 | func main() { 16 | s := "1234" 17 | x, err := strconv.Atoi(s) 18 | if err != nil { 19 | log.Fatalf("atoi failed: %v", err) 20 | } 21 | 22 | // ParseInt can be used instead of atoi to parse 23 | // numbers of different bases and widths. 24 | base := int(10) 25 | bitSize := int(64) 26 | y, err := strconv.ParseInt(s, base, bitSize) 27 | if err != nil { 28 | log.Fatalf("parse int failed: %v", err) 29 | } 30 | 31 | if y == x { 32 | println("x and y are equal") 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /kfugo/scratch/regexp/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "regexp" // Regular expressions. 9 | ) 10 | 11 | // Hint: MatchString method accepts string argument. 12 | // regexp.Regexp type has a method that accepts []byte argument. 13 | 14 | func main() { 15 | // Normal strings use "", raw strings use ``. 16 | // You don't need to escape special chars in raw strings, 17 | // this is why they are preffered for regexp patterns. 18 | re := regexp.MustCompile(`\d+.\d+`) 19 | 20 | // If statement can introduce variables into it's scope. 21 | if x := "132.0"; re.MatchString("132.0") { 22 | println("matched:", x) 23 | } else { 24 | println("not matched:", x) // x is also reachable in "else" branch 25 | } 26 | 27 | if x := []byte("abc"); re.MatchString(x) { 28 | println("matched:", x) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /kfugo/scratch/sort/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "fmt" // Formatted I/O with functions analogous to C's printf and scanf. 9 | "sort" // Functions for sorting 10 | ) 11 | 12 | // Hint: ":=" is only valid inside function scope. 13 | // It can't be used at top level (outside functions). 14 | 15 | lucky := 777 16 | 17 | func main() { 18 | xs := []int{4, 5, 1, 3, lucky} 19 | sort.Ints(xs) 20 | fmt.Printf("xs=%v\n", xs) 21 | 22 | var ys = []float32{4.4, 14.55, 0, 1} 23 | // Sort by using sorting predicate for "less". 24 | // This sorts in ASC order. 25 | sort.Slice(ys, func(i, j int) bool { 26 | return ys[i] < ys[j] 27 | }) 28 | fmt.Printf("ys=%v\n", ys) 29 | // This sorts in DESC order. 30 | sort.Slice(ys, func(i, j int) bool { 31 | return ys[i] > ys[j] 32 | }) 33 | fmt.Printf("ys=%v\n", ys) 34 | } 35 | -------------------------------------------------------------------------------- /kfugo/scratch/strings/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "fmt" // Formatted I/O with functions analogous to C's printf and scanf. 9 | ) 10 | 11 | // Hint: Go strings are immutable. 12 | 13 | func main() { 14 | s := "I❤Go" // Go string literals are in utf8. 15 | 16 | // For/range loop over string yields 4-byte (int32) wide "runes". 17 | // The [x:y] notation creates a substring (in Go it's called slicing). 18 | for i, c := range s[1:] { 19 | fmt.Printf("index=%d type=%T, value='%c'\n", i, c, c) 20 | } 21 | 22 | s[0] = 'a' 23 | 24 | // Use simple for to iterate over string individual bytes. 25 | for i := 0; i < len(s); i++ { 26 | c := s[i] 27 | fmt.Printf("index=%d type=%T, value='%c'\n", i, c, c) 28 | } 29 | } 30 | --------------------------------------------------------------------------------