├── .gitignore ├── README.md ├── TOC_EN.md ├── TOC_ES.md ├── code_samples ├── 000_temp │ └── 01-concurrency │ │ └── main.go ├── 001-hello-world │ └── main.go ├── 002-cross-compile │ └── main.go ├── 003-packages │ ├── cat │ │ └── info.go │ └── dog │ │ └── main.go ├── 004-ninja-level-nine │ ├── 01-goroutines-waitgroups │ │ └── main.go │ ├── 02-methods-sets │ │ └── main.go │ ├── 03-race-condition │ │ └── main.go │ ├── 04-mutex │ │ └── main.go │ ├── 05-atomic │ │ └── main.go │ └── 06-os-arch │ │ └── main.go ├── 005-channels │ ├── 01-channels-block │ │ ├── 01-does-not-run │ │ │ └── main.go │ │ ├── 02-successful-pass-of-value │ │ │ └── main.go │ │ ├── 03-succesful-buffer │ │ │ └── main.go │ │ ├── 04-unsuccesful-buffer │ │ │ └── main.go │ │ └── 05-succesful-buffer │ │ │ └── main.go │ ├── 02-directional-channels │ │ ├── 01 │ │ │ └── main.go │ │ ├── 02-does-not-work │ │ │ └── main.go │ │ ├── 03-does-not-work │ │ │ └── main.go │ │ ├── 04-using-with-funcs │ │ │ └── main.go │ │ └── 05-range-close │ │ │ └── main.go │ └── 03-select │ │ └── main.go ├── 006-error-handling │ ├── 00-check-errors │ │ ├── 01 │ │ │ └── main.go │ │ ├── 02 │ │ │ └── main.go │ │ ├── 03 │ │ │ └── main.go │ │ └── 04 │ │ │ ├── main.go │ │ │ └── names.txt │ ├── 01-fmt-println │ │ └── main.go │ ├── 02-log-println │ │ └── main.go │ ├── 03-log-set-output │ │ ├── log.txt │ │ └── main.go │ ├── 04-log-fatalln │ │ └── main.go │ ├── 05-log-panic │ │ └── main.go │ ├── 06-panic │ │ └── main.go │ └── 07-custom-errors │ │ ├── 01_errors-new │ │ └── main.go │ │ ├── 02_errors-new_var │ │ └── main.go │ │ ├── 03_fmt-errorf │ │ └── main.go │ │ ├── 04_fmt-errorf_var │ │ └── main.go │ │ └── 05_custom-type │ │ └── main.go ├── 007-documentation │ └── 01 │ │ ├── main.go │ │ └── mymath │ │ └── main.go ├── 008-ninja-level-twelve │ └── 01 │ │ ├── dog │ │ └── main.go │ │ └── main.go ├── 009-testing │ ├── 01-test │ │ ├── 01 │ │ │ ├── main.go │ │ │ └── main_test.go │ │ └── 02 │ │ │ ├── main.go │ │ │ └── main_test.go │ ├── 02-table-test │ │ ├── 01 │ │ │ ├── main.go │ │ │ └── main_test.go │ │ └── 02 │ │ │ ├── main.go │ │ │ └── main_test.go │ ├── 03-examples │ │ ├── 01 │ │ │ ├── acdc │ │ │ │ ├── main.go │ │ │ │ └── main_test.go │ │ │ └── main.go │ │ └── 02 │ │ │ ├── main.go │ │ │ └── mymathtwo │ │ │ ├── main.go │ │ │ └── main_test.go │ └── 04-benchmark │ │ ├── 00-live │ │ ├── main.go │ │ └── saying │ │ │ ├── c.out │ │ │ ├── main.go │ │ │ └── main_test.go │ │ ├── 01-greet │ │ ├── main.go │ │ └── main_test.go │ │ ├── 02-greet │ │ ├── main.go │ │ └── mystr │ │ │ ├── main.go │ │ │ └── main_test.go │ │ ├── 03-cat │ │ ├── main.go │ │ └── mystr │ │ │ ├── main.go │ │ │ └── main_test.go │ │ └── readme.md ├── 010-ninja-level-thirteen │ ├── 01 │ │ ├── finished │ │ │ ├── dog │ │ │ │ ├── c.out │ │ │ │ ├── main.go │ │ │ │ └── main_test.go │ │ │ └── main.go │ │ └── starting-code │ │ │ ├── dog │ │ │ └── main.go │ │ │ └── main.go │ ├── 02 │ │ ├── 01-code-starting │ │ │ ├── main.go │ │ │ ├── quote │ │ │ │ └── main.go │ │ │ └── word │ │ │ │ └── main.go │ │ └── 02-code-finished │ │ │ ├── main.go │ │ │ ├── quote │ │ │ └── main.go │ │ │ └── word │ │ │ ├── c.out │ │ │ ├── main.go │ │ │ └── main_test.go │ └── 03 │ │ ├── 01-code-starting │ │ ├── main.go │ │ └── mymath │ │ │ └── main.go │ │ └── 02-code-finished │ │ ├── main.go │ │ └── mymath │ │ ├── c.out │ │ ├── main.go │ │ └── main_test.go └── 011-code-samples │ ├── 01-file │ ├── 01-open │ │ ├── 01-ioutil-readall │ │ │ ├── main.go │ │ │ └── rumi.txt │ │ └── 02-bufio-newscanner │ │ │ ├── dalia-shevin.txt │ │ │ └── main.go │ └── 02-newfile │ │ ├── 01-write │ │ ├── dog-poem.txt │ │ └── main.go │ │ └── 02-copy │ │ ├── 01 │ │ ├── dog-poem.txt │ │ └── main.go │ │ └── 02-strings-newreader │ │ └── main.go │ ├── 02-donovan-kernighan │ ├── 02-structure │ │ ├── 01-fibonacci │ │ │ ├── main.go │ │ │ └── mymath │ │ │ │ ├── mymath.go │ │ │ │ └── mymath_test.go │ │ └── 02-celsius-farenheit │ │ │ ├── main.go │ │ │ └── tempconv │ │ │ ├── tempconv.go │ │ │ └── tempconv_test.go │ ├── 11-testing │ │ ├── 01 │ │ │ └── word │ │ │ │ ├── word.go │ │ │ │ └── word_test.go │ │ └── 02 │ │ │ └── word │ │ │ ├── word.go │ │ │ └── word_test.go │ └── readme.md │ └── readme.md ├── code_samples_es ├── 000_temp │ └── 01-concurrency │ │ └── main.go ├── 001-hello-world │ └── main.go ├── 002-cross-compile │ └── main.go ├── 003-packages │ ├── cat │ │ └── info.go │ └── dog │ │ └── main.go ├── 004-ninja-level-nine │ ├── 01-goroutines-waitgroups │ │ └── main.go │ ├── 02-methods-sets │ │ └── main.go │ ├── 03-race-condition │ │ └── main.go │ ├── 04-mutex │ │ └── main.go │ ├── 05-atomic │ │ └── main.go │ └── 06-os-arch │ │ └── main.go ├── 005-channels │ ├── 01-channels-block │ │ ├── 01-does-not-run │ │ │ └── main.go │ │ ├── 02-successful-pass-of-value │ │ │ └── main.go │ │ ├── 03-succesful-buffer │ │ │ └── main.go │ │ ├── 04-unsuccesful-buffer │ │ │ └── main.go │ │ └── 05-succesful-buffer │ │ │ └── main.go │ ├── 02-directional-channels │ │ ├── 01 │ │ │ └── main.go │ │ ├── 02-does-not-work │ │ │ └── main.go │ │ ├── 03-does-not-work │ │ │ └── main.go │ │ ├── 04-using-with-funcs │ │ │ └── main.go │ │ └── 05-range-close │ │ │ └── main.go │ └── 03-select │ │ └── main.go ├── 006-error-handling │ ├── 00-check-errors │ │ ├── 01 │ │ │ └── main.go │ │ ├── 02 │ │ │ └── main.go │ │ ├── 03 │ │ │ └── main.go │ │ └── 04 │ │ │ ├── main.go │ │ │ └── names.txt │ ├── 01-fmt-println │ │ └── main.go │ ├── 02-log-println │ │ └── main.go │ ├── 03-log-set-output │ │ ├── log.txt │ │ └── main.go │ ├── 04-log-fatalln │ │ └── main.go │ ├── 05-log-panic │ │ └── main.go │ ├── 06-panic │ │ └── main.go │ └── 07-custom-errors │ │ ├── 01_errors-new │ │ └── main.go │ │ ├── 02_errors-new_var │ │ └── main.go │ │ ├── 03_fmt-errorf │ │ └── main.go │ │ ├── 04_fmt-errorf_var │ │ └── main.go │ │ └── 05_custom-type │ │ └── main.go ├── 007-documentation │ └── 01 │ │ ├── main.go │ │ └── mymath │ │ └── main.go ├── 008-ninja-level-twelve │ └── 01 │ │ ├── dog │ │ └── main.go │ │ └── main.go ├── 009-testing │ ├── 01-test │ │ ├── 01 │ │ │ ├── main.go │ │ │ └── main_test.go │ │ └── 02 │ │ │ ├── main.go │ │ │ └── main_test.go │ ├── 02-table-test │ │ ├── 01 │ │ │ ├── main.go │ │ │ └── main_test.go │ │ └── 02 │ │ │ ├── main.go │ │ │ └── main_test.go │ ├── 03-examples │ │ ├── 01 │ │ │ ├── acdc │ │ │ │ ├── main.go │ │ │ │ └── main_test.go │ │ │ └── main.go │ │ └── 02 │ │ │ ├── main.go │ │ │ └── mymathtwo │ │ │ ├── main.go │ │ │ └── main_test.go │ └── 04-benchmark │ │ ├── 00-live │ │ ├── main.go │ │ └── saying │ │ │ ├── c.out │ │ │ ├── main.go │ │ │ └── main_test.go │ │ ├── 01-greet │ │ ├── main.go │ │ └── main_test.go │ │ ├── 02-greet │ │ ├── main.go │ │ └── mystr │ │ │ ├── main.go │ │ │ └── main_test.go │ │ ├── 03-cat │ │ ├── main.go │ │ └── mystr │ │ │ ├── main.go │ │ │ └── main_test.go │ │ └── readme.md ├── 010-ninja-level-thirteen │ ├── 01 │ │ ├── finished │ │ │ ├── dog │ │ │ │ ├── c.out │ │ │ │ ├── main.go │ │ │ │ └── main_test.go │ │ │ └── main.go │ │ └── starting-code │ │ │ ├── dog │ │ │ └── main.go │ │ │ └── main.go │ ├── 02 │ │ ├── 01-code-starting │ │ │ ├── main.go │ │ │ ├── quote │ │ │ │ └── main.go │ │ │ └── word │ │ │ │ └── main.go │ │ └── 02-code-finished │ │ │ ├── main.go │ │ │ ├── quote │ │ │ └── main.go │ │ │ └── word │ │ │ ├── c.out │ │ │ ├── main.go │ │ │ └── main_test.go │ └── 03 │ │ ├── 01-code-starting │ │ ├── main.go │ │ └── mymath │ │ │ └── main.go │ │ └── 02-code-finished │ │ ├── main.go │ │ └── mymath │ │ ├── c.out │ │ ├── main.go │ │ └── main_test.go └── 011-code-samples │ ├── 01-file │ ├── 01-open │ │ ├── 01-ioutil-readall │ │ │ ├── main.go │ │ │ └── rumi.txt │ │ └── 02-bufio-newscanner │ │ │ ├── dalia-shevin.txt │ │ │ └── main.go │ └── 02-newfile │ │ ├── 01-write │ │ ├── dog-poem.txt │ │ └── main.go │ │ └── 02-copy │ │ ├── 01 │ │ ├── dog-poem.txt │ │ └── main.go │ │ └── 02-strings-newreader │ │ └── main.go │ ├── 02-donovan-kernighan │ ├── 02-structure │ │ ├── 01-fibonacci │ │ │ ├── main.go │ │ │ └── mymath │ │ │ │ ├── mymath.go │ │ │ │ └── mymath_test.go │ │ └── 02-celsius-farenheit │ │ │ ├── main.go │ │ │ └── tempconv │ │ │ ├── tempconv.go │ │ │ └── tempconv_test.go │ ├── 11-testing │ │ ├── 01 │ │ │ └── word │ │ │ │ ├── word.go │ │ │ │ └── word_test.go │ │ └── 02 │ │ │ └── word │ │ │ ├── word.go │ │ │ └── word_test.go │ └── readme.md │ └── readme.md ├── code_samples_it └── temp.txt ├── section_02 ├── 2.01.md ├── 2.02.md ├── 2.03.md ├── 2.04.md ├── 2.05.md ├── 2.06.md ├── 2.07.md ├── 2.08.md └── 2.09.md ├── section_02_it └── temp.txt ├── section_02_ja ├── 2.1.md ├── 2.2.md ├── 2.3.md ├── 2.4.md ├── 2.5.md ├── 2.6.md ├── 2.7.md ├── 2.8.md └── 2.9.md ├── section_03 ├── 3.01.md ├── 3.02.md ├── 3.03.md ├── 3.04.md ├── 3.05.md └── 3.06.md ├── section_03_ja ├── 3.1.md ├── 3.2.md ├── 3.3.md ├── 3.4.md ├── 3.5.md └── 3.6.md ├── section_04 ├── 4.01.md ├── 4.02.md ├── 4.03.md ├── 4.04.md ├── 4.05.md ├── 4.06.md ├── 4.07.md └── 4.08.md ├── section_04_ja ├── 4.1.md ├── 4.2.md ├── 4.3.md ├── 4.4.md ├── 4.5.md ├── 4.6.md ├── 4.7.md └── 4.8.md ├── section_05 ├── 5.01.md ├── 5.02.md ├── 5.03.md ├── 5.04.md ├── 5.05.md ├── 5.06.md ├── 5.07.md └── 5.07a.md ├── section_05_ja ├── 5.01.md ├── 5.02.md ├── 5.03.md ├── 5.04.md ├── 5.05.md ├── 5.06.md ├── 5.07.md └── 5.07a.md ├── section_06 ├── 6.01.md ├── 6.02.md ├── 6.03.md ├── 6.04.md ├── 6.05.md ├── 6.06.md ├── 6.07.md ├── 6.08.md ├── 6.09.md ├── 6.10.md ├── 6.11.md └── 6.12.md └── section_07 ├── 7.01.md ├── 7.02.md ├── 7.03.md ├── 7.04.md ├── 7.05.md ├── 7.06.md ├── 7.07.md ├── 7.08.md ├── 7.09.md └── 7.10.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | 26 | # WebStorm 27 | *.iml 28 | 29 | # Directory-based project format: 30 | .idea/ 31 | .idea/workspace.xml 32 | **/.idea/workspace.xml 33 | 34 | # mac hidden files 35 | .DS_Store 36 | 37 | #other 38 | node_modules/ 39 | bower_components/ 40 | .tmp 41 | .sass-cache 42 | builds/**/images/* 43 | *.ogg 44 | *.mp3 45 | *.mp4 46 | #*.png 47 | #*.jpeg 48 | 49 | # security / ssl 50 | *.pem 51 | *.xxjson 52 | 53 | # Elastic Beanstalk Files 54 | .elasticbeanstalk/* 55 | !.elasticbeanstalk/*.cfg.yml 56 | !.elasticbeanstalk/*.global.yml 57 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Learn How To Code: Google's Go (golang) Programming Language 2 | 3 | This is the compendium material for Todd McLeod's course Learn How To Code: Google's Go (golang) Programming Language, available online at [GreaterCommons.com](https://greatercommons.com/). 4 | 5 | ## Table of Contents 6 | 7 | * [English](TOC_EN.md) 8 | 9 | * [Español](TOC_ES.md) 10 | 11 | ## Contribution Guidelines 12 | 13 | To contribute, just [fork this repository](https://github.com/GoesToEleven/go-programming#fork-destination-box) make a change, push it to your fork, then open a pull request. Check out this [video tutorial](https://www.youtube.com/watch?v=iYIWwob0wKg) for how to fork and createa a pull request. 14 | 15 | -------------------------------------------------------------------------------- /TOC_EN.md: -------------------------------------------------------------------------------- 1 | # Learn How To Code: Google’s Go (golang) Programming Language 2 | 3 | ## Section 2: Variables, Values, & Type 4 | 5 | * [2.01 Playground](section_02/2.01.md) 6 | * [2.02 Hello World](section_02/2.02.md) 7 | * [2.03 Short Declaration Operator](section_02/2.03.md) 8 | * [2.04 The Var Keyword](section_02/2.04.md) 9 | * [2.05 Exploring Type](section_02/2.05.md) 10 | * [2.06 Zero Value](section_02/2.06.md) 11 | * [2.07 The fmt Package](section_02/2.07.md) 12 | * [2.08 Creating Your Own Type](section_02/2.08.md) 13 | * [2.09 Conversion, Not Casting](section_02/2.09.md) 14 | 15 | ## Section 3: Exercises - Level 1 16 | 17 | * [3.01 Hands-on Exercise #1](section_03/3.01.md) 18 | * [3.02 Hands-on Exercise #2](section_03/3.02.md) 19 | * [3.03 Hands-on Exercise #3](section_03/3.03.md) 20 | * [3.04 Hands-on Exercise #4](section_03/3.04.md) 21 | * [3.05 Hands-on Exercise #5](section_03/3.05.md) 22 | * [3.06 Hands-on Exercise #6](section_03/3.06.md) 23 | 24 | ## Section 4: Programming Fundamentals 25 | 26 | * [4.01 Bool Type](section_04/4.01.md) 27 | * [4.02 How Computers Work](section_04/4.02.md) 28 | * [4.03 Numeric Types](section_04/4.03.md) 29 | * [4.04 String Type](section_04/4.04.md) 30 | * [4.05 Numeral Systems](section_04/4.05.md) 31 | * [4.06 Constants](section_04/4.06.md) 32 | * [4.07 Iota](section_04/4.07.md) 33 | * [4.08 Bit Shifting](section_04/4.08.md) 34 | 35 | ## Section 5: Exercises - Level 2 36 | 37 | * [5.01 Hands-on Exercise #1](section_05/5.01.md) 38 | * [5.02 Hands-on Exercise #2](section_05/5.02.md) 39 | * [5.03 Hands-on Exercise #3](section_05/5.03.md) 40 | * [5.04 Hands-on Exercise #4](section_05/5.04.md) 41 | * [5.05 Hands-on Exercise #5](section_05/5.05.md) 42 | * [5.06 Hands-on Exercise #6](section_05/5.06.md) 43 | * [5.07 Hands-on Exercise #7](section_05/5.07.md) 44 | * [5.07a Hands-on Exercise #7 Answers](section_05/5.07a.md) 45 | 46 | ## Section 6: Control Flow 47 | 48 | * [6.01 Understanding Control Flow](section_06/6.01.md) 49 | * [6.02 Loop - Init, Condition, Post](section_06/6.02.md) 50 | * [6.03 Loop - Nested Loops](section_06/6.03.md) 51 | * [6.04 Loop - For Statement](section_06/6.04.md) 52 | * [6.05 Loop - Break & Continue](section_06/6.05.md) 53 | * [6.06 Loop - Printing ASCII](section_06/6.06.md) 54 | * [6.07 Conditional - If Statement](section_06/6.07.md) 55 | * [6.08 Conditional - If, Else if, Else](section_06/6.08.md) 56 | * [6.09 Loop, Conditional, Modulus](section_06/6.09.md) 57 | * [6.10 Conditional - Switch Statement](section_06/6.10.md) 58 | * [6.11 Conditional - Switch Statement Documentation](section_6/6.11.md) 59 | * [6.12 Conditional Logic Operators ](section_06/6.12.md) 60 | 61 | ## Section 7: Exercises - Level 3 62 | 63 | * [7.01 Hands-on Exercise #1](section_07/7.01.md) 64 | * [7.02 Hands-on Exercise #2](section_07/7.02.md) 65 | * [7.03 Hands-on Exercise #3](section_07/7.03.md) 66 | * [7.04 Hands-on Exercise #4](section_07/7.04.md) 67 | * [7.05 Hands-on Exercise #5](section_07/7.05.md) 68 | * [7.06 Hands-on Exercise #6](section_07/7.06.md) 69 | * [7.07 Hands-on Exercise #7](section_07/7.07.md) 70 | * [7.08 Hands-on Exercise #8](section_07/7.08.md) 71 | * [7.09 Hands-on Exercise #9](section_07/7.09.md) 72 | * [7.10 Hands-on Exercise #10](section_07/7.10.md) 73 | 74 | -------------------------------------------------------------------------------- /TOC_ES.md: -------------------------------------------------------------------------------- 1 | # Aprendiendo a Programar: El Lenguaje de Programación de Google Go 2 | 3 | ## Sección 2: Variables, Valores y Tipos 4 | 5 | * [2.01 Playground](section_02_es/2.01.md) 6 | * [2.02 Hola Mundo](section_02_es/2.02.md) 7 | * [2.03 Operador de Declaración Corta](section_02_es/2.03.md) 8 | * [2.04 La Palabra Clave Var](section_02_es/2.04.md) 9 | * [2.05 Explorando Type](section_02_es/2.05.md) 10 | * [2.06 El Valor Cero](section_02_es/2.06.md) 11 | * [2.07 El Paquete fmt](section_02_es/2.07.md) 12 | * [2.08 Creando Tu Propio Tipo](section_02_es/2.08.md) 13 | * [2.09 Conversión, No Casting](section_02_es/2.09.md) 14 | 15 | ## Sección 3: Ejercicios - Nivel 1 16 | 17 | * [3.01 Ejercicio Práctico #1](section_03_es/3.01.md) 18 | * [3.02 Ejercicio Práctico #2](section_03_es/3.02.md) 19 | * [3.03 Ejercicio Práctico #3](section_03_es/3.03.md) 20 | * [3.04 Ejercicio Práctico #4](section_03_es/3.04.md) 21 | * [3.05 Ejercicio Práctico #5](section_03_es/3.05.md) 22 | * [3.06 Ejercicio Práctico #6](section_03_es/3.06.md) 23 | 24 | ## Sección 4: Fundamentos de Programación 25 | 26 | * [4.01 Tipo Booleano](section_04_es/4.01.md) 27 | * [4.02 Cómo Funciona La Computadora](section_04_es/4.02.md) 28 | * [4.03 Tipos Numéricos](section_04_es/4.03.md) 29 | * [4.04 Tipos String](section_04_es/4.04.md) 30 | * [4.05 Sistemas Numéricos](section_04_es/4.05.md) 31 | * [4.06 Constantes](section_04_es/4.06.md) 32 | * [4.07 Iota](section_04_es/4.07.md) 33 | * [4.08 Desplazamineto de Bits](section_04_es/4.08.md) 34 | 35 | ## Sección 5: Ejercicios - Nivel 2 36 | 37 | * [5.01 Ejercicio Práctico #1](section_05_es/5.01.md) 38 | * [5.02 Ejercicio Práctico #2](section_05_es/5.02.md) 39 | * [5.03 Ejercicio Práctico #3](section_05_es/5.03.md) 40 | * [5.04 Ejercicio Práctico #4](section_05_es/5.04.md) 41 | * [5.05 Ejercicio Práctico #5](section_05_es/5.05.md) 42 | * [5.06 Ejercicio Práctico #6](section_05_es/5.06.md) 43 | * [5.07 Ejercicio Práctico #7](section_05_es/5.07.md) 44 | * [5.07a Ejercicio Práctico #7 Respuestas1](section_05_es/5.07a.md) 45 | 46 | ## Sección 6: Control de Flujo 47 | 48 | * [6.01 Entendiendo el Control de Flujo](section_06_es/6.01.md) 49 | * [6.02 Loop - Init, Condition, Post](section_06_es/6.02.md) 50 | * [6.03 Loop - Loops Anidados](section_06_es/6.03.md) 51 | * [6.04 Loop - Declaración For](section_06_es/6.04.md) 52 | * [6.05 Loop - Break Y Continue](section_06_es/6.05.md) 53 | * [6.06 Loop - Imprimiendo ASCII](section_06_es/6.06.md) 54 | * [6.07 Condicional - Declaración If](section_06_es/6.07.md) 55 | * [6.08 Condicional - If, Else if, Else](section_06_es/6.08.md) 56 | * [6.09 Loop, Condicional, Módulo](section_06_es/6.09.md) 57 | * [6.10 Condicional - Declaración Switch](section_06_es/6.10.md) 58 | * [6.11 Conditional - Documentación de la Declaración Switch](section_6_es/6.11.md) 59 | * [6.12 Operadores Lóigicos Condicionales](section_06_es/6.12.md) 60 | 61 | ## Sección 7: Ejercicios - Nivel 3 62 | 63 | * [7.01 Ejercicio Práctico #1](section_07_es/7.01.md) 64 | * [7.02 Ejercicio Práctico #2](section_07_es/7.02.md) 65 | * [7.03 Ejercicio Práctico #3](section_07_es/7.03.md) 66 | * [7.04 Ejercicio Práctico #4](section_07_es/7.04.md) 67 | * [7.05 Ejercicio Práctico #5](section_07_es/7.05.md) 68 | * [7.06 Ejercicio Práctico #6](section_07_es/7.06.md) 69 | * [7.07 Ejercicio Práctico #7](section_07_es/7.07.md) 70 | * [7.08 Ejercicio Práctico #8](section_07_es/7.08.md) 71 | * [7.09 Ejercicio Práctico #9](section_07_es/7.09.md) 72 | * [7.10 Ejercicio Práctico #10](section_07_es/7.10.md) 73 | 74 | -------------------------------------------------------------------------------- /code_samples/000_temp/01-concurrency/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func main() { 8 | q := make(chan int) 9 | c := gen(q) 10 | 11 | receive(c, q) 12 | 13 | fmt.Println("about to exit") 14 | } 15 | 16 | func receive(c, q <-chan int) { 17 | for { 18 | select { 19 | case v := <-c: 20 | fmt.Println(v) 21 | case <-q: 22 | return 23 | } 24 | 25 | } 26 | } 27 | 28 | func gen(q chan<- int) <-chan int { 29 | c := make(chan int) 30 | 31 | go func() { 32 | for i := 0; i < 100; i++ { 33 | c <- i 34 | } 35 | q <- 1 36 | close(c) 37 | }() 38 | 39 | return c 40 | } 41 | -------------------------------------------------------------------------------- /code_samples/001-hello-world/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println("Hello World") 7 | } 8 | -------------------------------------------------------------------------------- /code_samples/002-cross-compile/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | ) 7 | 8 | func main() { 9 | fmt.Printf("runtime: %s\narchitecture: %s\n", runtime.GOOS, runtime.GOARCH) 10 | } 11 | -------------------------------------------------------------------------------- /code_samples/003-packages/cat/info.go: -------------------------------------------------------------------------------- 1 | package cat 2 | 3 | import "fmt" 4 | 5 | func Hello() { 6 | fmt.Println("Hello from cat") 7 | } 8 | 9 | func Eats() { 10 | fmt.Println("Cat eats birds") 11 | } 12 | -------------------------------------------------------------------------------- /code_samples/003-packages/dog/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/003-packages/cat" 6 | ) 7 | 8 | func main() { 9 | fmt.Println("Hello from dog.") 10 | cat.Hello() 11 | cat.Eats() 12 | } 13 | -------------------------------------------------------------------------------- /code_samples/004-ninja-level-nine/01-goroutines-waitgroups/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | "sync" 7 | ) 8 | 9 | func main() { 10 | 11 | fmt.Println("begin cpu", runtime.NumCPU()) 12 | fmt.Println("begin gs", runtime.NumGoroutine()) 13 | 14 | var wg sync.WaitGroup 15 | wg.Add(2) 16 | 17 | go func() { 18 | fmt.Println("hello from thing one") 19 | wg.Done() 20 | }() 21 | 22 | go func() { 23 | fmt.Println("hello from thing two") 24 | wg.Done() 25 | }() 26 | 27 | fmt.Println("mid cpu", runtime.NumCPU()) 28 | fmt.Println("mid gs", runtime.NumGoroutine()) 29 | 30 | wg.Wait() 31 | 32 | fmt.Println("about to exit") 33 | fmt.Println("end cpu", runtime.NumCPU()) 34 | fmt.Println("end gs", runtime.NumGoroutine()) 35 | } 36 | -------------------------------------------------------------------------------- /code_samples/004-ninja-level-nine/02-methods-sets/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type person struct { 6 | first string 7 | } 8 | 9 | type human interface { 10 | speak() 11 | } 12 | 13 | func (p *person) speak() { 14 | fmt.Println("Hello") 15 | } 16 | 17 | func saySomething(h human) { 18 | h.speak() 19 | } 20 | 21 | func main() { 22 | p1 := person{ 23 | first: "James", 24 | } 25 | 26 | saySomething(&p1) 27 | 28 | // does not work 29 | // saySomething(p1) 30 | 31 | p1.speak() 32 | } 33 | -------------------------------------------------------------------------------- /code_samples/004-ninja-level-nine/03-race-condition/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | "sync" 7 | ) 8 | 9 | func main() { 10 | var wg sync.WaitGroup 11 | 12 | incrementer := 0 13 | gs := 100 14 | wg.Add(gs) 15 | 16 | for i := 0; i < gs; i++ { 17 | go func() { 18 | v := incrementer 19 | runtime.Gosched() 20 | v++ 21 | incrementer = v 22 | fmt.Println(incrementer) 23 | wg.Done() 24 | }() 25 | } 26 | wg.Wait() 27 | fmt.Println("end value:", incrementer) 28 | } 29 | -------------------------------------------------------------------------------- /code_samples/004-ninja-level-nine/04-mutex/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | ) 7 | 8 | func main() { 9 | var wg sync.WaitGroup 10 | 11 | incrementer := 0 12 | gs := 100 13 | wg.Add(gs) 14 | var m sync.Mutex 15 | 16 | for i := 0; i < gs; i++ { 17 | go func() { 18 | m.Lock() 19 | v := incrementer 20 | v++ 21 | incrementer = v 22 | fmt.Println(incrementer) 23 | m.Unlock() 24 | wg.Done() 25 | }() 26 | } 27 | wg.Wait() 28 | fmt.Println("end value:", incrementer) 29 | } 30 | -------------------------------------------------------------------------------- /code_samples/004-ninja-level-nine/05-atomic/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | "sync/atomic" 7 | ) 8 | 9 | func main() { 10 | var wg sync.WaitGroup 11 | var incrementer int64 12 | 13 | gs := 100 14 | wg.Add(gs) 15 | 16 | for i := 0; i < gs; i++ { 17 | go func() { 18 | atomic.AddInt64(&incrementer, 1) 19 | fmt.Println(atomic.LoadInt64(&incrementer)) 20 | wg.Done() 21 | }() 22 | } 23 | wg.Wait() 24 | fmt.Println("end value:", incrementer) 25 | } 26 | -------------------------------------------------------------------------------- /code_samples/004-ninja-level-nine/06-os-arch/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(runtime.GOOS, runtime.GOARCH) 10 | } 11 | -------------------------------------------------------------------------------- /code_samples/005-channels/01-channels-block/01-does-not-run/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan int) 7 | 8 | c <- 42 9 | 10 | fmt.Println(<-c) 11 | } 12 | -------------------------------------------------------------------------------- /code_samples/005-channels/01-channels-block/02-successful-pass-of-value/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan int) 7 | 8 | go func() { 9 | c <- 42 10 | }() 11 | 12 | fmt.Println(<-c) 13 | } 14 | -------------------------------------------------------------------------------- /code_samples/005-channels/01-channels-block/03-succesful-buffer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan int, 1) 7 | 8 | c <- 42 9 | 10 | fmt.Println(<-c) 11 | } 12 | -------------------------------------------------------------------------------- /code_samples/005-channels/01-channels-block/04-unsuccesful-buffer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan int, 1) 7 | 8 | c <- 42 9 | c <- 43 10 | 11 | fmt.Println(<-c) 12 | } 13 | -------------------------------------------------------------------------------- /code_samples/005-channels/01-channels-block/05-succesful-buffer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan int, 2) 7 | 8 | c <- 42 9 | c <- 43 10 | 11 | fmt.Println(<-c) 12 | fmt.Println(<-c) 13 | } 14 | -------------------------------------------------------------------------------- /code_samples/005-channels/02-directional-channels/01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan int, 2) 7 | 8 | c <- 42 9 | c <- 43 10 | 11 | fmt.Println(<-c) 12 | fmt.Println(<-c) 13 | fmt.Println("-----") 14 | fmt.Printf("%T\n", c) 15 | } 16 | -------------------------------------------------------------------------------- /code_samples/005-channels/02-directional-channels/02-does-not-work/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan<- int, 2) 7 | 8 | c <- 42 9 | c <- 43 10 | 11 | fmt.Println(<-c) 12 | fmt.Println(<-c) 13 | fmt.Println("-----") 14 | fmt.Printf("%T\n", c) 15 | } 16 | -------------------------------------------------------------------------------- /code_samples/005-channels/02-directional-channels/03-does-not-work/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(<-chan int, 2) 7 | 8 | c <- 42 9 | c <- 43 10 | 11 | fmt.Println(<-c) 12 | fmt.Println(<-c) 13 | fmt.Println("-----") 14 | fmt.Printf("%T\n", c) 15 | } 16 | -------------------------------------------------------------------------------- /code_samples/005-channels/02-directional-channels/04-using-with-funcs/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan int) 7 | 8 | // send 9 | go foo(c) 10 | 11 | // receive 12 | bar(c) 13 | 14 | fmt.Println("about to exit") 15 | } 16 | 17 | // send 18 | func foo(c chan<- int) { 19 | c <- 42 20 | } 21 | 22 | // receive 23 | func bar(c <-chan int) { 24 | fmt.Println(<-c) 25 | } 26 | -------------------------------------------------------------------------------- /code_samples/005-channels/02-directional-channels/05-range-close/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan int) 7 | 8 | // send 9 | go func() { 10 | for i := 0; i < 5; i++ { 11 | c <- i 12 | } 13 | close(c) 14 | }() 15 | 16 | // receive 17 | for v := range c { 18 | fmt.Println(v) 19 | } 20 | 21 | fmt.Println("about to exit") 22 | } 23 | -------------------------------------------------------------------------------- /code_samples/005-channels/03-select/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | eve := make(chan int) 7 | odd := make(chan int) 8 | quit := make(chan int) 9 | 10 | // send 11 | go send(eve, odd, quit) 12 | 13 | // receive 14 | receive(eve, odd, quit) 15 | 16 | fmt.Println("about to exit") 17 | } 18 | 19 | func receive(e, o, q <-chan int) { 20 | for { 21 | select { 22 | case v := <-e: 23 | fmt.Println("from the eve channel:", v) 24 | case v := <-o: 25 | fmt.Println("from the odd channel:", v) 26 | case v := <-q: 27 | fmt.Println("from the quit channel:", v) 28 | return 29 | } 30 | } 31 | } 32 | 33 | func send(e, o, q chan<- int) { 34 | for i := 0; i < 100; i++ { 35 | if i%2 == 0 { 36 | e <- i 37 | } else { 38 | o <- i 39 | } 40 | } 41 | q <- 0 42 | } 43 | -------------------------------------------------------------------------------- /code_samples/006-error-handling/00-check-errors/01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | n, err := fmt.Println("Hello") 7 | if err != nil { 8 | fmt.Println(err) 9 | } 10 | fmt.Println(n) 11 | } 12 | -------------------------------------------------------------------------------- /code_samples/006-error-handling/00-check-errors/02/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var answer1, answer2, answer3 string 7 | 8 | fmt.Print("Name: ") 9 | _, err := fmt.Scan(&answer1) 10 | if err != nil { 11 | panic(err) 12 | } 13 | 14 | fmt.Print("Fav Food: ") 15 | _, err = fmt.Scan(&answer2) 16 | if err != nil { 17 | panic(err) 18 | } 19 | 20 | fmt.Print("Fav Sport: ") 21 | _, err = fmt.Scan(&answer3) 22 | if err != nil { 23 | panic(err) 24 | } 25 | 26 | fmt.Println(answer1, answer2, answer3) 27 | 28 | } 29 | -------------------------------------------------------------------------------- /code_samples/006-error-handling/00-check-errors/03/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "os" 7 | "strings" 8 | ) 9 | 10 | func main() { 11 | f, err := os.Create("names.txt") 12 | if err != nil { 13 | fmt.Println(err) 14 | return 15 | } 16 | defer f.Close() 17 | 18 | r := strings.NewReader("James Bond") 19 | 20 | io.Copy(f, r) 21 | } 22 | -------------------------------------------------------------------------------- /code_samples/006-error-handling/00-check-errors/04/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "os" 7 | ) 8 | 9 | func main() { 10 | f, err := os.Open("names.txt") 11 | if err != nil { 12 | fmt.Println(err) 13 | return 14 | } 15 | defer f.Close() 16 | 17 | bs, err := ioutil.ReadAll(f) 18 | if err != nil { 19 | fmt.Println(err) 20 | return 21 | } 22 | 23 | fmt.Println(string(bs)) 24 | } 25 | -------------------------------------------------------------------------------- /code_samples/006-error-handling/00-check-errors/04/names.txt: -------------------------------------------------------------------------------- 1 | James Bond -------------------------------------------------------------------------------- /code_samples/006-error-handling/01-fmt-println/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | ) 7 | 8 | func main() { 9 | _, err := os.Open("no-file.txt") 10 | if err != nil { 11 | fmt.Println("err happened", err) 12 | // log.Println("err happened", err) 13 | // log.Fatalln(err) 14 | // panic(err) 15 | } 16 | } 17 | 18 | // Println formats using the default formats for its operands and writes to standard output. 19 | -------------------------------------------------------------------------------- /code_samples/006-error-handling/02-log-println/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | ) 7 | 8 | func main() { 9 | _, err := os.Open("no-file.txt") 10 | if err != nil { 11 | // fmt.Println("err happened", err) 12 | log.Println("err happened", err) 13 | // log.Fatalln(err) 14 | // panic(err) 15 | } 16 | } 17 | 18 | /* 19 | Package log implements a simple logging package ... writes to standard error and prints the date and time of each logged message ... 20 | */ 21 | 22 | // log.Println calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Println. 23 | -------------------------------------------------------------------------------- /code_samples/006-error-handling/03-log-set-output/log.txt: -------------------------------------------------------------------------------- 1 | 2017/08/07 13:16:32 err happened open no-file.txt: no such file or directory 2 | -------------------------------------------------------------------------------- /code_samples/006-error-handling/03-log-set-output/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | ) 8 | 9 | func main() { 10 | f, err := os.Create("log.txt") 11 | if err != nil { 12 | fmt.Println(err) 13 | } 14 | defer f.Close() 15 | log.SetOutput(f) 16 | 17 | f2, err := os.Open("no-file.txt") 18 | if err != nil { 19 | // fmt.Println("err happened", err) 20 | log.Println("err happened", err) 21 | // log.Fatalln(err) 22 | // panic(err) 23 | } 24 | defer f2.Close() 25 | 26 | fmt.Println("check the log.txt file in the directory") 27 | } 28 | 29 | // Println calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Println. 30 | -------------------------------------------------------------------------------- /code_samples/006-error-handling/04-log-fatalln/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | ) 8 | 9 | func main() { 10 | defer foo() 11 | _, err := os.Open("no-file.txt") 12 | if err != nil { 13 | // fmt.Println("err happened", err) 14 | // log.Println("err happened", err) 15 | log.Fatalln(err) 16 | // panic(err) 17 | } 18 | } 19 | 20 | func foo() { 21 | fmt.Println("When os.Exit() is called, deferred functions don't run") 22 | } 23 | 24 | /* 25 | ... the Fatal functions call os.Exit(1) after writing the log message ... 26 | */ 27 | 28 | // Fatalln is equivalent to Println() followed by a call to os.Exit(1). 29 | -------------------------------------------------------------------------------- /code_samples/006-error-handling/05-log-panic/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | ) 7 | 8 | func main() { 9 | _, err := os.Open("no-file.txt") 10 | if err != nil { 11 | // fmt.Println("err happened", err) 12 | // log.Println("err happened", err) 13 | // log.Fatalln(err) 14 | log.Panicln(err) 15 | // panic(err) 16 | } 17 | } 18 | 19 | /* 20 | Panicln is equivalent to Println() followed by a call to panic(). 21 | */ 22 | 23 | // Fatalln is equivalent to Println() followed by a call to os.Exit(1). 24 | -------------------------------------------------------------------------------- /code_samples/006-error-handling/06-panic/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | ) 6 | 7 | func main() { 8 | _, err := os.Open("no-file.txt") 9 | if err != nil { 10 | // fmt.Println("err happened", err) 11 | // log.Println("err happened", err) 12 | // log.Fatalln(err) 13 | // log.Panicln(err) 14 | panic(err) 15 | } 16 | } 17 | 18 | // http://godoc.org/builtin#panic 19 | -------------------------------------------------------------------------------- /code_samples/006-error-handling/07-custom-errors/01_errors-new/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "log" 6 | ) 7 | 8 | func main() { 9 | _, err := sqrt(-10) 10 | if err != nil { 11 | log.Fatalln(err) 12 | } 13 | } 14 | 15 | func sqrt(f float64) (float64, error) { 16 | if f < 0 { 17 | return 0, errors.New("norgate math: square root of negative number") 18 | } 19 | return 42, nil 20 | } 21 | -------------------------------------------------------------------------------- /code_samples/006-error-handling/07-custom-errors/02_errors-new_var/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "log" 7 | ) 8 | 9 | var ErrNorgateMath = errors.New("norgate math: square root of negative number") 10 | 11 | func main() { 12 | fmt.Printf("%T\n", ErrNorgateMath) 13 | _, err := sqrt(-10) 14 | if err != nil { 15 | log.Fatalln(err) 16 | } 17 | } 18 | 19 | func sqrt(f float64) (float64, error) { 20 | if f < 0 { 21 | return 0, ErrNorgateMath 22 | } 23 | return 42, nil 24 | } 25 | 26 | // see use of errors.New in standard library: 27 | // http://golang.org/src/pkg/bufio/bufio.go 28 | // http://golang.org/src/pkg/io/io.go 29 | -------------------------------------------------------------------------------- /code_samples/006-error-handling/07-custom-errors/03_fmt-errorf/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | ) 7 | 8 | func main() { 9 | _, err := sqrt(-10.23) 10 | if err != nil { 11 | log.Fatalln(err) 12 | } 13 | } 14 | 15 | func sqrt(f float64) (float64, error) { 16 | if f < 0 { 17 | return 0, fmt.Errorf("norgate math again: square root of negative number: %v", f) 18 | } 19 | return 42, nil 20 | } 21 | -------------------------------------------------------------------------------- /code_samples/006-error-handling/07-custom-errors/04_fmt-errorf_var/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | ) 7 | 8 | func main() { 9 | _, err := sqrt(-10.23) 10 | if err != nil { 11 | log.Fatalln(err) 12 | } 13 | } 14 | 15 | func sqrt(f float64) (float64, error) { 16 | if f < 0 { 17 | ErrNorgateMath := fmt.Errorf("norgate math again: square root of negative number: %v", f) 18 | return 0, ErrNorgateMath 19 | } 20 | return 42, nil 21 | } 22 | -------------------------------------------------------------------------------- /code_samples/006-error-handling/07-custom-errors/05_custom-type/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | ) 7 | 8 | type norgateMathError struct { 9 | lat string 10 | long string 11 | err error 12 | } 13 | 14 | func (n norgateMathError) Error() string { 15 | return fmt.Sprintf("a norgate math error occured: %v %v %v", n.lat, n.long, n.err) 16 | } 17 | 18 | func main() { 19 | _, err := sqrt(-10.23) 20 | if err != nil { 21 | log.Println(err) 22 | } 23 | } 24 | 25 | func sqrt(f float64) (float64, error) { 26 | if f < 0 { 27 | nme := fmt.Errorf("norgate math redux: square root of negative number: %v", f) 28 | return 0, norgateMathError{"50.2289 N", "99.4656 W", nme} 29 | } 30 | return 42, nil 31 | } 32 | 33 | // see use of structs with error type in standard library: 34 | // 35 | // http://golang.org/pkg/net/#OpError 36 | // http://golang.org/src/pkg/net/dial.go 37 | // http://golang.org/src/pkg/net/net.go 38 | // 39 | // http://golang.org/src/pkg/encoding/json/decode.go 40 | -------------------------------------------------------------------------------- /code_samples/007-documentation/01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/007-documentation/01/mymath" 6 | ) 7 | 8 | func main() { 9 | fmt.Println("2 + 3 =", mymath.Sum(2, 3)) 10 | fmt.Println("4 + 7 =", mymath.Sum(4, 7)) 11 | fmt.Println("5 + 9 =", mymath.Sum(5, 9)) 12 | } 13 | -------------------------------------------------------------------------------- /code_samples/007-documentation/01/mymath/main.go: -------------------------------------------------------------------------------- 1 | // Package mymath provides ACME inc math solutions. 2 | package mymath 3 | 4 | // Sum adds an unlimited number of values of type int. 5 | func Sum(xi ...int) int { 6 | sum := 0 7 | for _, v := range xi { 8 | sum += v 9 | } 10 | return sum 11 | } 12 | -------------------------------------------------------------------------------- /code_samples/008-ninja-level-twelve/01/dog/main.go: -------------------------------------------------------------------------------- 1 | // Package dog allows us to more fully understand dogs. 2 | package dog 3 | 4 | // Years converts human years to dog years. 5 | func Years(n int) int { 6 | return n * 7 7 | } 8 | -------------------------------------------------------------------------------- /code_samples/008-ninja-level-twelve/01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/008-ninja-level-twelve/01/dog" 6 | ) 7 | 8 | type canine struct { 9 | name string 10 | age int 11 | } 12 | 13 | func main() { 14 | fido := canine{ 15 | name: "Fido", 16 | age: dog.Years(10), 17 | } 18 | fmt.Println(fido) 19 | } 20 | -------------------------------------------------------------------------------- /code_samples/009-testing/01-test/01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println("2 + 3 =", mySum(2, 3)) 7 | fmt.Println("4 + 7 =", mySum(4, 7)) 8 | fmt.Println("5 + 9 =", mySum(5, 9)) 9 | } 10 | 11 | func mySum(xi ...int) int { 12 | sum := 0 13 | for _, v := range xi { 14 | sum += v 15 | } 16 | return sum 17 | } 18 | -------------------------------------------------------------------------------- /code_samples/009-testing/01-test/01/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "testing" 4 | 5 | func TestMySum(t *testing.T) { 6 | x := mySum(2, 3) 7 | if x != 5 { 8 | t.Error("Expected", 5, "Got", x) 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /code_samples/009-testing/01-test/02/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println("2 + 3 =", myAdd(2, 3)) 7 | fmt.Println("5 + 7 =", myAdd(5, 7)) 8 | } 9 | 10 | func myAdd(xi ...int) int { 11 | var sum int 12 | for _, v := range xi { 13 | sum += v 14 | } 15 | return sum 16 | } 17 | -------------------------------------------------------------------------------- /code_samples/009-testing/01-test/02/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "testing" 4 | 5 | func TestMyAdd(t *testing.T) { 6 | if myAdd(2, 3) != 2+3 { 7 | t.Error("Expected", 5, "Got", myAdd(2, 3)) 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /code_samples/009-testing/02-table-test/01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println("2 + 3 =", mySum(2, 3)) 7 | fmt.Println("4 + 7 =", mySum(4, 7)) 8 | fmt.Println("5 + 9 =", mySum(5, 9)) 9 | } 10 | 11 | func mySum(xi ...int) int { 12 | sum := 0 13 | for _, v := range xi { 14 | sum += v 15 | } 16 | return sum 17 | } 18 | -------------------------------------------------------------------------------- /code_samples/009-testing/02-table-test/01/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "testing" 4 | 5 | func TestMySum(t *testing.T) { 6 | 7 | type test struct { 8 | data []int 9 | answer int 10 | } 11 | 12 | tests := []test{ 13 | test{[]int{21, 21}, 42}, 14 | test{[]int{3, 4, 5}, 12}, 15 | test{[]int{1, 1}, 2}, 16 | test{[]int{-1, 0, 1}, 0}, 17 | } 18 | 19 | for _, v := range tests { 20 | x := mySum(v.data...) 21 | if x != v.answer { 22 | t.Error("Expected", v.answer, "Got", x) 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /code_samples/009-testing/02-table-test/02/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println("2 + 3 =", myAdd(2, 3)) 7 | fmt.Println("5 + 7 =", myAdd(5, 7)) 8 | } 9 | 10 | func myAdd(xi ...int) int { 11 | var sum int 12 | for _, v := range xi { 13 | sum += v 14 | } 15 | return sum 16 | } 17 | -------------------------------------------------------------------------------- /code_samples/009-testing/02-table-test/02/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "testing" 4 | 5 | func TestMyAdd(t *testing.T) { 6 | type test struct { 7 | data []int 8 | answer int 9 | } 10 | 11 | tests := []test{ 12 | test{[]int{2, 3, 4}, 9}, 13 | test{[]int{42, 43, 44}, 129}, 14 | test{[]int{5, 7}, 12}, 15 | test{[]int{7, 7, 7}, 21}, 16 | test{[]int{14, 18}, 32}, 17 | test{[]int{12, 19}, 31}, 18 | test{[]int{1, 1}, 2}, 19 | } 20 | 21 | for _, v := range tests { 22 | x := myAdd(v.data...) 23 | if x != v.answer { 24 | t.Error("Expected", v.answer, "Got", x) 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /code_samples/009-testing/03-examples/01/acdc/main.go: -------------------------------------------------------------------------------- 1 | // Package acdc asks if you are ready to rock 2 | package acdc 3 | 4 | // Sum adds an unlimited number of values of type int 5 | func Sum(xi ...int) int { 6 | s := 0 7 | for _, v := range xi { 8 | s += v 9 | } 10 | return s 11 | } 12 | -------------------------------------------------------------------------------- /code_samples/009-testing/03-examples/01/acdc/main_test.go: -------------------------------------------------------------------------------- 1 | package acdc 2 | 3 | import "fmt" 4 | 5 | func ExampleSum() { 6 | fmt.Println(Sum(2, 3)) 7 | // Output: 8 | // 5 9 | } 10 | -------------------------------------------------------------------------------- /code_samples/009-testing/03-examples/01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/009-testing/03-examples/01/acdc" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(acdc.Sum(2, 3)) 10 | fmt.Println(acdc.Sum(2, 3, 4, 5, 6, 7, 8, 9)) 11 | } 12 | -------------------------------------------------------------------------------- /code_samples/009-testing/03-examples/02/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/007-documentation/01/mymath" 6 | ) 7 | 8 | func main() { 9 | fmt.Println("2 + 3 =", mymath.Sum(2, 3)) 10 | fmt.Println("4 + 7 =", mymath.Sum(4, 7)) 11 | fmt.Println("5 + 9 =", mymath.Sum(5, 9)) 12 | } 13 | -------------------------------------------------------------------------------- /code_samples/009-testing/03-examples/02/mymathtwo/main.go: -------------------------------------------------------------------------------- 1 | // Package mymathtwo provides ACME inc math solutions. 2 | package mymathtwo 3 | 4 | // Sum adds an unlimited number of values of type int. 5 | func Sum(xi ...int) int { 6 | sum := 0 7 | for _, v := range xi { 8 | sum += v 9 | } 10 | return sum 11 | } 12 | -------------------------------------------------------------------------------- /code_samples/009-testing/03-examples/02/mymathtwo/main_test.go: -------------------------------------------------------------------------------- 1 | package mymathtwo 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/007-documentation/01/mymath" 6 | "testing" 7 | ) 8 | 9 | func TestSum(t *testing.T) { 10 | 11 | type test struct { 12 | data []int 13 | answer int 14 | } 15 | 16 | tests := []test{ 17 | test{[]int{21, 21}, 42}, 18 | test{[]int{3, 4, 5}, 12}, 19 | test{[]int{1, 1}, 2}, 20 | test{[]int{-1, 0, 1}, 0}, 21 | } 22 | 23 | for _, v := range tests { 24 | x := Sum(v.data...) 25 | if x != v.answer { 26 | t.Error("Expected", v.answer, "Got", x) 27 | } 28 | } 29 | } 30 | 31 | func ExampleSum() { 32 | fmt.Println(Sum(2, 3)) 33 | // Output: 34 | // 5 35 | } 36 | -------------------------------------------------------------------------------- /code_samples/009-testing/04-benchmark/00-live/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/009-testing/04-benchmark/00-live/saying" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(saying.Greet("James")) 10 | } 11 | -------------------------------------------------------------------------------- /code_samples/009-testing/04-benchmark/00-live/saying/c.out: -------------------------------------------------------------------------------- 1 | mode: set 2 | github.com/GoesToEleven/go-programming/code_samples/009-testing/04-benchmark/00-live/saying/main.go:5.29,7.2 1 1 3 | -------------------------------------------------------------------------------- /code_samples/009-testing/04-benchmark/00-live/saying/main.go: -------------------------------------------------------------------------------- 1 | package saying 2 | 3 | import "fmt" 4 | 5 | func Greet(s string) string { 6 | return fmt.Sprint("Welcome my dear ", s) 7 | } 8 | -------------------------------------------------------------------------------- /code_samples/009-testing/04-benchmark/00-live/saying/main_test.go: -------------------------------------------------------------------------------- 1 | package saying 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestGreet(t *testing.T) { 9 | s := Greet("James") 10 | if s != "Welcome my dear James" { 11 | t.Error("got", s, "expected", "Welcome my dear James") 12 | } 13 | } 14 | 15 | func ExampleGreet() { 16 | fmt.Println(Greet("James")) 17 | // Output: 18 | // Welcome my dear James 19 | } 20 | 21 | func BenchmarkGreet(b *testing.B) { 22 | for i := 0; i < b.N; i++ { 23 | Greet("James") 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /code_samples/009-testing/04-benchmark/01-greet/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(Greet("James")) 7 | } 8 | 9 | func Greet(s string) string { 10 | return fmt.Sprint("Hello my dear, ", s) 11 | } 12 | -------------------------------------------------------------------------------- /code_samples/009-testing/04-benchmark/01-greet/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestGreet(t *testing.T) { 8 | s := Greet("James") 9 | if s != "Hello my dear, James" { 10 | t.Error("got", s, "want", "Hello my dear, James") 11 | } 12 | } 13 | 14 | func BenchmarkGreet(b *testing.B) { 15 | for i := 0; i < b.N; i++ { 16 | Greet("James") 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /code_samples/009-testing/04-benchmark/02-greet/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/009-testing/04-benchmark/02-greet/mystr" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(mystr.Greet("James")) 10 | } 11 | -------------------------------------------------------------------------------- /code_samples/009-testing/04-benchmark/02-greet/mystr/main.go: -------------------------------------------------------------------------------- 1 | package mystr 2 | 3 | import "fmt" 4 | 5 | func Greet(s string) string { 6 | return fmt.Sprint("Hello my dear, ", s) 7 | } 8 | -------------------------------------------------------------------------------- /code_samples/009-testing/04-benchmark/02-greet/mystr/main_test.go: -------------------------------------------------------------------------------- 1 | package mystr 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestGreet(t *testing.T) { 9 | s := Greet("James") 10 | if s != "Hello my dear, James" { 11 | t.Error("got", s, "want", "Hello my dear, James") 12 | } 13 | } 14 | 15 | func ExampleGreet() { 16 | fmt.Println(Greet("James")) 17 | // Output: 18 | // Hello my dear, James 19 | } 20 | 21 | func BenchmarkGreet(b *testing.B) { 22 | for i := 0; i < b.N; i++ { 23 | Greet("James") 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /code_samples/009-testing/04-benchmark/03-cat/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/009-testing/04-benchmark/03-cat/mystr" 6 | "strings" 7 | ) 8 | 9 | const s = "We ask ourselves, Who am I to be brilliant, gorgeous, talented, fabulous? Actually, who are you not to be? Your playing small does not serve the world. There is nothing enlightened about shrinking so that other people won't feel insecure around you. We are all meant to shine, as children do. We were born to make manifest the glory that is within us. It's not just in some of us; it's in everyone. And as we let our own light shine, we unconsciously give other people permission to do the same. As we are liberated from our own fear, our presence automatically liberates others. - Marianne Williamson" 10 | 11 | func main() { 12 | 13 | xs := strings.Split(s, " ") 14 | 15 | for _, v := range xs { 16 | fmt.Println(v) 17 | } 18 | 19 | fmt.Printf("\n%s\n", mystr.Cat(xs)) 20 | fmt.Printf("\n%s\n\n", mystr.Join(xs)) 21 | } 22 | -------------------------------------------------------------------------------- /code_samples/009-testing/04-benchmark/03-cat/mystr/main.go: -------------------------------------------------------------------------------- 1 | package mystr 2 | 3 | import "strings" 4 | 5 | func Cat(xs []string) string { 6 | s := xs[0] 7 | for _, v := range xs[1:] { 8 | s += " " 9 | s += v 10 | } 11 | return s 12 | } 13 | 14 | func Join(xs []string) string { 15 | return strings.Join(xs, " ") 16 | } 17 | -------------------------------------------------------------------------------- /code_samples/009-testing/04-benchmark/03-cat/mystr/main_test.go: -------------------------------------------------------------------------------- 1 | package mystr 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | "testing" 7 | ) 8 | 9 | func TestCat(t *testing.T) { 10 | s := "Shaken not stirred" 11 | xs := strings.Split(s, " ") 12 | s = Cat(xs) 13 | if s != "Shaken not stirred" { 14 | t.Error("got", s, "want", "Shaken not stirred") 15 | } 16 | } 17 | 18 | func TestJoin(t *testing.T) { 19 | s := "Shaken not stirred" 20 | xs := strings.Split(s, " ") 21 | s = Join(xs) 22 | if s != "Shaken not stirred" { 23 | t.Error("got", s, "want", "Shaken not stirred") 24 | } 25 | } 26 | 27 | func ExampleCat() { 28 | s := "Shaken not stirred" 29 | xs := strings.Split(s, " ") 30 | fmt.Println(Cat(xs)) 31 | // Output: 32 | // Shaken not stirred 33 | } 34 | 35 | func ExampleJoin() { 36 | s := "Shaken not stirred" 37 | xs := strings.Split(s, " ") 38 | fmt.Println(Join(xs)) 39 | // Output: 40 | // Shaken not stirred 41 | } 42 | 43 | const s = "We ask ourselves, Who am I to be brilliant, gorgeous, talented, fabulous? Actually, who are you not to be? Your playing small does not serve the world. There is nothing enlightened about shrinking so that other people won't feel insecure around you. We are all meant to shine, as children do. We were born to make manifest the glory that is within us. It's not just in some of us; it's in everyone. And as we let our own light shine, we unconsciously give other people permission to do the same. As we are liberated from our own fear, our presence automatically liberates others. - Marianne Williamson" 44 | 45 | var xs []string 46 | 47 | func BenchmarkCat(b *testing.B) { 48 | xs = strings.Split(s, " ") 49 | b.ResetTimer() 50 | for i := 0; i < b.N; i++ { 51 | Cat(xs) 52 | } 53 | } 54 | 55 | func BenchmarkJoin(b *testing.B) { 56 | xs = strings.Split(s, " ") 57 | b.ResetTimer() 58 | for i := 0; i < b.N; i++ { 59 | Join(xs) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /code_samples/009-testing/04-benchmark/readme.md: -------------------------------------------------------------------------------- 1 | # Remember to BET 2 | - Benchmark 3 | - Example 4 | - Test 5 | 6 | ``` 7 | BenchmarkCat(b *testing.B) 8 | ExampleCat() 9 | TestCat(t *testing.T) 10 | ``` 11 | 12 | # Commands 13 | 14 | ``` 15 | godoc -http=:8080 16 | 17 | go test 18 | go test -bench . 19 | go test -cover 20 | go test -coverprofile c.out 21 | go tool cover -html=c.out 22 | ``` 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/01/finished/dog/c.out: -------------------------------------------------------------------------------- 1 | mode: set 2 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/01/finished/dog/main.go:5.23,7.2 1 1 3 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/01/finished/dog/main.go:10.26,12.25 2 1 4 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/01/finished/dog/main.go:15.2,15.14 1 1 5 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/01/finished/dog/main.go:12.25,14.3 1 1 6 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/01/finished/dog/main.go: -------------------------------------------------------------------------------- 1 | // Package dog allows us to more fully understand dogs. 2 | package dog 3 | 4 | // Years converts human years to dog years. 5 | func Years(n int) int { 6 | return n * 7 7 | } 8 | 9 | // YearsTwo converts human years to dog years. 10 | func YearsTwo(n int) int { 11 | count := 0 12 | for i := 0; i < n; i++ { 13 | count += 7 14 | } 15 | return count 16 | } 17 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/01/finished/dog/main_test.go: -------------------------------------------------------------------------------- 1 | package dog 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestYears(t *testing.T) { 9 | n := Years(10) 10 | if n != 70 { 11 | t.Error("got", n, "want", 70) 12 | } 13 | } 14 | 15 | func TestYearsTwo(t *testing.T) { 16 | n := YearsTwo(10) 17 | if n != 70 { 18 | t.Error("got", n, "want", 70) 19 | } 20 | } 21 | 22 | func ExampleYears() { 23 | fmt.Println(Years(10)) 24 | // Output: 25 | // 70 26 | } 27 | 28 | func ExampleYearsTwo() { 29 | fmt.Println(YearsTwo(10)) 30 | // Output: 31 | // 70 32 | } 33 | 34 | func BenchmarkYears(b *testing.B) { 35 | for i := 0; i < b.N; i++ { 36 | Years(10) 37 | } 38 | } 39 | 40 | func BenchmarkYearsTwo(b *testing.B) { 41 | for i := 0; i < b.N; i++ { 42 | YearsTwo(10) 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/01/finished/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/01/starting-code/dog" 6 | ) 7 | 8 | type canine struct { 9 | name string 10 | age int 11 | } 12 | 13 | func main() { 14 | fido := canine{ 15 | name: "Fido", 16 | age: dog.Years(10), 17 | } 18 | fmt.Println(fido) 19 | fmt.Println(dog.YearsTwo(20)) 20 | } 21 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/01/starting-code/dog/main.go: -------------------------------------------------------------------------------- 1 | // Package dog allows us to more fully understand dogs. 2 | package dog 3 | 4 | // Years converts human years to dog years. 5 | func Years(n int) int { 6 | return n * 7 7 | } 8 | 9 | // YearsTwo converts human years to dog years. 10 | func YearsTwo(n int) int { 11 | count := 0 12 | for i := 0; i < n; i++ { 13 | count += 7 14 | } 15 | return count 16 | } 17 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/01/starting-code/main.go: -------------------------------------------------------------------------------- 1 | package starting_code 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/01/starting-code/dog" 6 | ) 7 | 8 | type canine struct { 9 | name string 10 | age int 11 | } 12 | 13 | func main() { 14 | fido := canine{ 15 | name: "Fido", 16 | age: dog.Years(10), 17 | } 18 | fmt.Println(fido) 19 | fmt.Println(dog.YearsTwo(20)) 20 | } 21 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/02/01-code-starting/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/01-code-starting/quote" 6 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/01-code-starting/word" 7 | ) 8 | 9 | func main() { 10 | fmt.Println(word.Count(quote.SunAlso)) 11 | 12 | for k, v := range word.UseCount(quote.SunAlso) { 13 | fmt.Println(v, k) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/02/01-code-starting/word/main.go: -------------------------------------------------------------------------------- 1 | package word 2 | 3 | import "strings" 4 | 5 | // no need to write an example for this one 6 | // writing a test for this one is a bonus challenge; harder 7 | func UseCount(s string) map[string]int { 8 | xs := strings.Fields(s) 9 | m := make(map[string]int) 10 | for _, v := range xs { 11 | m[v]++ 12 | } 13 | return m 14 | } 15 | 16 | func Count(s string) int { 17 | // write the code for this func 18 | } 19 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/02/02-code-finished/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/02-code-finished/quote" 6 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/02-code-finished/word" 7 | ) 8 | 9 | func main() { 10 | fmt.Println(word.Count(quote.SunAlso)) 11 | 12 | for k, v := range word.UseCount(quote.SunAlso) { 13 | fmt.Println(v, k) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/02/02-code-finished/word/c.out: -------------------------------------------------------------------------------- 1 | mode: set 2 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/02-code-finished/word/main.go:7.40,10.23 3 1 3 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/02-code-finished/word/main.go:13.2,13.10 1 1 4 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/02-code-finished/word/main.go:10.23,12.3 1 1 5 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/02-code-finished/word/main.go:17.26,20.2 2 1 6 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/02/02-code-finished/word/main.go: -------------------------------------------------------------------------------- 1 | // Package word provides custom functions for working with strings and words. 2 | package word 3 | 4 | import "strings" 5 | 6 | // UseCount returns the number of times each word is used in a string. 7 | func UseCount(s string) map[string]int { 8 | xs := strings.Fields(s) 9 | m := make(map[string]int) 10 | for _, v := range xs { 11 | m[v]++ 12 | } 13 | return m 14 | } 15 | 16 | // Count returns the number of words in a string. 17 | func Count(s string) int { 18 | xs := strings.Fields(s) 19 | return len(xs) 20 | } 21 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/02/02-code-finished/word/main_test.go: -------------------------------------------------------------------------------- 1 | package word 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/02-code-finished/quote" 6 | "testing" 7 | ) 8 | 9 | func TestUseCount(t *testing.T) { 10 | m := UseCount("one two three three three") 11 | for k, v := range m { 12 | switch k { 13 | case "one": 14 | if v != 1 { 15 | t.Error("got", v, "want", 1) 16 | } 17 | case "two": 18 | if v != 1 { 19 | t.Error("got", v, "want", 1) 20 | } 21 | case "three": 22 | if v != 3 { 23 | t.Error("got", v, "want", 1) 24 | } 25 | } 26 | } 27 | } 28 | 29 | func TestCount(t *testing.T) { 30 | n := Count("one two three") 31 | if n != 3 { 32 | t.Error("got", n, "want", 3) 33 | } 34 | } 35 | 36 | func ExampleCount() { 37 | fmt.Println(Count("one two three")) 38 | // Output: 39 | // 3 40 | } 41 | 42 | func BenchmarkCount(b *testing.B) { 43 | for i := 0; i < b.N; i++ { 44 | Count(quote.SunAlso) 45 | } 46 | } 47 | 48 | func BenchmarkUseCount(b *testing.B) { 49 | for i := 0; i < b.N; i++ { 50 | UseCount(quote.SunAlso) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/03/01-code-starting/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/03/01-code-starting/mymath" 6 | ) 7 | 8 | func main() { 9 | xxi := gen() 10 | for _, v := range xxi { 11 | fmt.Println(mymath.CenteredAvg(v)) 12 | } 13 | } 14 | 15 | func gen() [][]int { 16 | a := []int{1, 4, 6, 8, 100} 17 | b := []int{0, 8, 10, 1000} 18 | c := []int{9000, 4, 10, 8, 6, 12} 19 | d := []int{123, 744, 140, 200} 20 | e := [][]int{a, b, c, d} 21 | return e 22 | } 23 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/03/01-code-starting/mymath/main.go: -------------------------------------------------------------------------------- 1 | package mymath 2 | 3 | import "sort" 4 | 5 | // CenteredAvg computes the average of a list of numbers 6 | // after removing the largest and smallest values. 7 | func CenteredAvg(xi []int) float64 { 8 | sort.Ints(xi) 9 | xi = xi[1:(len(xi) - 1)] 10 | 11 | n := 0 12 | for _, v := range xi { 13 | n += v 14 | } 15 | 16 | f := float64(n) / float64(len(xi)) 17 | return f 18 | } 19 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/03/02-code-finished/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/03/02-code-finished/mymath" 6 | ) 7 | 8 | func main() { 9 | xxi := gen() 10 | for _, v := range xxi { 11 | fmt.Println(mymath.CenteredAvg(v)) 12 | } 13 | } 14 | 15 | // gen generates data to pass into CenteredAvg 16 | func gen() [][]int { 17 | a := []int{1, 4, 6, 8, 100} 18 | b := []int{0, 8, 10, 1000} 19 | c := []int{9000, 4, 10, 8, 6, 12} 20 | d := []int{123, 744, 140, 200} 21 | e := [][]int{a, b, c, d} 22 | return e 23 | } 24 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/03/02-code-finished/mymath/c.out: -------------------------------------------------------------------------------- 1 | mode: set 2 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/03/02-code-finished/mymath/main.go:8.36,13.23 4 1 3 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/03/02-code-finished/mymath/main.go:17.2,18.10 2 1 4 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/03/02-code-finished/mymath/main.go:13.23,15.3 1 1 5 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/03/02-code-finished/mymath/main.go: -------------------------------------------------------------------------------- 1 | // Package mymath provides math solutions relevant to our company. 2 | package mymath 3 | 4 | import "sort" 5 | 6 | // CenteredAvg computes the average of a list of numbers 7 | // after removing the largest and smallest values. 8 | func CenteredAvg(xi []int) float64 { 9 | sort.Ints(xi) 10 | xi = xi[1:(len(xi) - 1)] 11 | 12 | n := 0 13 | for _, v := range xi { 14 | n += v 15 | } 16 | 17 | f := float64(n) / float64(len(xi)) 18 | return f 19 | } 20 | -------------------------------------------------------------------------------- /code_samples/010-ninja-level-thirteen/03/02-code-finished/mymath/main_test.go: -------------------------------------------------------------------------------- 1 | package mymath 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestCenteredAvg(t *testing.T) { 9 | type test struct { 10 | data []int 11 | answer float64 12 | } 13 | 14 | tests := []test{ 15 | test{[]int{10, 20, 40, 60, 80}, 40}, 16 | test{[]int{2, 4, 6, 8, 10, 12}, 7}, 17 | test{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9}, 5}, 18 | } 19 | 20 | for _, v := range tests { 21 | f := CenteredAvg(v.data) 22 | if f != v.answer { 23 | t.Error("got", f, "want", v.answer) 24 | } 25 | } 26 | 27 | } 28 | 29 | func ExampleCenteredAvg() { 30 | fmt.Println(CenteredAvg([]int{1, 2, 4, 6, 9})) 31 | // Output: 32 | // 4 33 | } 34 | 35 | func BenchmarkCenteredAvg(b *testing.B) { 36 | for i := 0; i < b.N; i++ { 37 | CenteredAvg([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10000}) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /code_samples/011-code-samples/01-file/01-open/01-ioutil-readall/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "log" 7 | "os" 8 | ) 9 | 10 | func main() { 11 | f, err := os.Open("rumi.txt") 12 | if err != nil { 13 | log.Fatalf("error opening file: %v", err) 14 | } 15 | defer f.Close() 16 | 17 | bs, err := ioutil.ReadAll(f) 18 | if err != nil { 19 | log.Fatalf("error reading file: %v", err) 20 | } 21 | 22 | fmt.Println(string(bs)) 23 | } 24 | -------------------------------------------------------------------------------- /code_samples/011-code-samples/01-file/01-open/01-ioutil-readall/rumi.txt: -------------------------------------------------------------------------------- 1 | Do you know what you are? 2 | You are a manuscript oƒ a divine letter. 3 | You are a mirror reflecting a noble face. 4 | This universe is not outside of you. 5 | Look inside yourself; 6 | everything that you want, 7 | you are already that. -------------------------------------------------------------------------------- /code_samples/011-code-samples/01-file/01-open/02-bufio-newscanner/dalia-shevin.txt: -------------------------------------------------------------------------------- 1 | I will find myself waist deep in high summer grass. 2 | The humming shock of the golden light. 3 | And I will hear them before I see them and know right away who is bounding across the field to meet me. 4 | All my good dogs will come then, their wet noses bumping against my palms, their hot panting, their rough faithful tongues. 5 | Their eyes young and shiny again. 6 | The wiry scruff of their fur, the unspeakable softness of their bellies, their velvet ears against my cheeks. 7 | I will bend to them, my face covered with their kisses, my hands full of them. 8 | In the grass I will let them knock me down. -------------------------------------------------------------------------------- /code_samples/011-code-samples/01-file/01-open/02-bufio-newscanner/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "strings" 9 | ) 10 | 11 | func main() { 12 | f, err := os.Open("dalia-shevin.txt") 13 | if err != nil { 14 | log.Fatalf("error opening file: %v", err) 15 | } 16 | defer f.Close() 17 | 18 | scanner := bufio.NewScanner(f) 19 | for scanner.Scan() { 20 | line := scanner.Text() 21 | if len(line) > 0 { 22 | fmt.Println(strings.ToUpper(line)) 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /code_samples/011-code-samples/01-file/02-newfile/01-write/dog-poem.txt: -------------------------------------------------------------------------------- 1 | If you can sit quietly after difficult news, If in financial down-times you can remain perfectly calm, If you can love unconditionally and see your neighbours travel to fantastic places without a twinge of jealously, If you can happily eat whatever is put on your plate, And if you can fall asleep after a day of running around without a drink or a pill, If you can always find contentment wherever you are, You are probably a dog. -------------------------------------------------------------------------------- /code_samples/011-code-samples/01-file/02-newfile/01-write/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io/ioutil" 5 | "log" 6 | "os" 7 | ) 8 | 9 | func main() { 10 | f, err := os.Open("dog-poem.txt") 11 | if err != nil { 12 | log.Fatalf("error opening file: %v", err) 13 | } 14 | defer f.Close() 15 | 16 | bs, err := ioutil.ReadAll(f) 17 | if err != nil { 18 | log.Fatalf("error reading file: %v", err) 19 | } 20 | 21 | nf, err := os.Create("newFile.txt") 22 | if err != nil { 23 | log.Fatalf("error creating file: %v", err) 24 | } 25 | defer nf.Close() 26 | 27 | _, err = nf.Write(bs) 28 | if err != nil { 29 | log.Fatalf("error writing file: %v", err) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /code_samples/011-code-samples/01-file/02-newfile/02-copy/01/dog-poem.txt: -------------------------------------------------------------------------------- 1 | If you can sit quietly after difficult news, If in financial down-times you can remain perfectly calm, If you can love unconditionally and see your neighbours travel to fantastic places without a twinge of jealously, If you can happily eat whatever is put on your plate, And if you can fall asleep after a day of running around without a drink or a pill, If you can always find contentment wherever you are, You are probably a dog. -------------------------------------------------------------------------------- /code_samples/011-code-samples/01-file/02-newfile/02-copy/01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io" 5 | "io/ioutil" 6 | "log" 7 | "os" 8 | ) 9 | 10 | func main() { 11 | f, err := os.Open("dog-poem.txt") 12 | if err != nil { 13 | log.Fatalf("error opening file: %v", err) 14 | } 15 | defer f.Close() 16 | 17 | bs, err := ioutil.ReadAll(f) 18 | if err != nil { 19 | log.Fatalf("error reading file: %v", err) 20 | } 21 | 22 | nf, err := os.Create("newFile.txt") 23 | if err != nil { 24 | log.Fatalf("error creating file: %v", err) 25 | } 26 | defer nf.Close() 27 | 28 | _, err = io.Copy(nf, f) 29 | if err != nil { 30 | log.Fatalf("error copying file: %v", err) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /code_samples/011-code-samples/01-file/02-newfile/02-copy/02-strings-newreader/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io" 5 | "io/ioutil" 6 | "log" 7 | "os" 8 | "strings" 9 | ) 10 | 11 | func main() { 12 | nf, err := os.Create("newFile.txt") 13 | if err != nil { 14 | log.Fatalf("error creating file: %v", err) 15 | } 16 | defer nf.Close() 17 | 18 | s := ` 19 | Don’t surrender your loneliness So quickly. 20 | Let it cut more deep. Let it ferment and season you 21 | as few human or even divine ingredients can. 22 | - Hafiz 23 | ` 24 | 25 | rdr := strings.NewReader(s) 26 | 27 | _, err = io.Copy(nf, rdr) 28 | if err != nil { 29 | log.Fatalf("error copying to file: %v", err) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /code_samples/011-code-samples/02-donovan-kernighan/02-structure/01-fibonacci/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/011-code-samples/02-donovan-kernighan/02-structure/01-fibonacci/mymath" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(mymath.Fib(0)) 10 | fmt.Println(mymath.Fib(1)) 11 | fmt.Println(mymath.Fib(2)) 12 | fmt.Println(mymath.Fib(3)) 13 | fmt.Println(mymath.Fib(4)) 14 | fmt.Println(mymath.Fib(5)) 15 | fmt.Println(mymath.Fib(6)) 16 | fmt.Println(mymath.Fib(7)) 17 | fmt.Println(mymath.Fib(8)) 18 | } 19 | -------------------------------------------------------------------------------- /code_samples/011-code-samples/02-donovan-kernighan/02-structure/01-fibonacci/mymath/mymath.go: -------------------------------------------------------------------------------- 1 | package mymath 2 | 3 | // Fib returns the nth number in the Fibonacci sequence. 4 | // Fibonacci sequence adds up the previous two numbers: 5 | // 0 1 1 2 3 5 8 13 21 6 | func Fib(n int) int { 7 | x, y := 0, 1 8 | for i := 0; i < n; i++ { 9 | x, y = y, x+y 10 | } 11 | return x 12 | } 13 | -------------------------------------------------------------------------------- /code_samples/011-code-samples/02-donovan-kernighan/02-structure/01-fibonacci/mymath/mymath_test.go: -------------------------------------------------------------------------------- 1 | package mymath 2 | 3 | import "testing" 4 | 5 | // Fibonacci sequence adds up the previous two numbers: 6 | // 0 1 1 2 3 5 8 13 21 7 | func TestFib(t *testing.T) { 8 | tests := []struct { 9 | input int 10 | want int 11 | }{ 12 | {0, 0}, 13 | {1, 1}, 14 | {2, 1}, 15 | {3, 2}, 16 | {4, 3}, 17 | {5, 5}, 18 | {6, 8}, 19 | {7, 13}, 20 | {8, 21}, 21 | } 22 | 23 | for _, test := range tests { 24 | if got := Fib(test.input); got != test.want { 25 | t.Errorf(`got Fib(%d) = %d wanted %d`, test.input, got, test.want) 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /code_samples/011-code-samples/02-donovan-kernighan/02-structure/02-celsius-farenheit/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /code_samples/011-code-samples/02-donovan-kernighan/02-structure/02-celsius-farenheit/tempconv/tempconv.go: -------------------------------------------------------------------------------- 1 | // Package tempconv performs Celsius and Fahrenheit temperature computations. 2 | package tempconv 3 | 4 | type Celsius float64 5 | type Fahrenheit float64 6 | 7 | const ( 8 | AbsoluteZeroC Celsius = -273.15 9 | FreezingC Celsius = 0 10 | BoilingC Celsius = 100 11 | ) 12 | 13 | func CToF(c Celsius) Fahrenheit { 14 | return Fahrenheit(c*9/5 + 32) 15 | } 16 | 17 | func FToC(f Fahrenheit) Celsius { 18 | return Celsius((f - 32) * 5 / 9) 19 | } 20 | -------------------------------------------------------------------------------- /code_samples/011-code-samples/02-donovan-kernighan/02-structure/02-celsius-farenheit/tempconv/tempconv_test.go: -------------------------------------------------------------------------------- 1 | package tempconv 2 | -------------------------------------------------------------------------------- /code_samples/011-code-samples/02-donovan-kernighan/11-testing/01/word/word.go: -------------------------------------------------------------------------------- 1 | // Package word provides utilities for word games. 2 | package word 3 | 4 | // IsPalidrome reports whether s reads the same forward and backward. 5 | func IsPalindrome(s string) bool { 6 | for i := range s { 7 | if s[i] != s[(len(s)-1)-i] { 8 | return false 9 | } 10 | } 11 | return true 12 | } 13 | -------------------------------------------------------------------------------- /code_samples/011-code-samples/02-donovan-kernighan/11-testing/01/word/word_test.go: -------------------------------------------------------------------------------- 1 | package word 2 | 3 | import "testing" 4 | 5 | func TestIsPalindrome(t *testing.T) { 6 | if !IsPalindrome("mom") { 7 | t.Error(`IsPalindrome("mom") = false`) 8 | } 9 | if !IsPalindrome("kayak") { 10 | t.Error(`IsPalindrome("kayak") = false`) 11 | } 12 | } 13 | 14 | func TestNonPalindrome(t *testing.T) { 15 | if IsPalindrome("dog") { 16 | t.Error(`IsPalindrone("dog") = true`) 17 | } 18 | } 19 | 20 | func TestFrenchPalindrone(t *testing.T) { 21 | s := "été" 22 | if !IsPalindrome(s) { 23 | t.Errorf(`IsPalindrone(%q) = false`, s) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /code_samples/011-code-samples/02-donovan-kernighan/11-testing/02/word/word.go: -------------------------------------------------------------------------------- 1 | // Package word provides utilities for word games. 2 | package word 3 | 4 | import "unicode" 5 | 6 | // IsPalidrome reports whether s reads the same forward and backward. 7 | func IsPalindrome(s string) bool { 8 | var letters []rune 9 | for _, r := range s { 10 | if unicode.IsLetter(r) { 11 | letters = append(letters, unicode.ToLower(r)) 12 | } 13 | } 14 | for i := range letters { 15 | if letters[i] != letters[(len(letters)-1)-i] { 16 | return false 17 | } 18 | } 19 | return true 20 | } 21 | -------------------------------------------------------------------------------- /code_samples/011-code-samples/02-donovan-kernighan/11-testing/02/word/word_test.go: -------------------------------------------------------------------------------- 1 | package word 2 | 3 | import "testing" 4 | 5 | func TestIsPalindrome(t *testing.T) { 6 | tests := []struct { 7 | input string 8 | want bool 9 | }{ 10 | {"", true}, 11 | {"a", true}, 12 | {"aa", true}, 13 | {"ab", false}, 14 | {"mom", true}, 15 | {"kayak", true}, 16 | {"dog", false}, 17 | {"été", true}, 18 | {"amanaplanacanalpanama", true}, 19 | {"", true}, 20 | {"", true}, 21 | } 22 | 23 | for _, test := range tests { 24 | if got := IsPalindrome(test.input); got != test.want { 25 | t.Errorf(`IsPalindrone(%q) = %v`, test.input, got) 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /code_samples/011-code-samples/02-donovan-kernighan/readme.md: -------------------------------------------------------------------------------- 1 | All of the code in this folder comes from Donovan & Kernighan's book on Go, or is inpsired by their book. -------------------------------------------------------------------------------- /code_samples/011-code-samples/readme.md: -------------------------------------------------------------------------------- 1 | This code is not covered in a video lecture. 2 | 3 | The code in this folder provides examples of code I like. 4 | 5 | This code has been provided so that you can look at it and learn from it. 6 | 7 | To learn more about Go programming, come join my "Go Web Dev" course! 8 | 9 | :) 10 | -------------------------------------------------------------------------------- /code_samples_es/000_temp/01-concurrency/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func main() { 8 | q := make(chan int) 9 | c := gen(q) 10 | 11 | receive(c, q) 12 | 13 | fmt.Println("about to exit") 14 | } 15 | 16 | func receive(c, q <-chan int) { 17 | for { 18 | select { 19 | case v := <-c: 20 | fmt.Println(v) 21 | case <-q: 22 | return 23 | } 24 | 25 | } 26 | } 27 | 28 | func gen(q chan<- int) <-chan int { 29 | c := make(chan int) 30 | 31 | go func() { 32 | for i := 0; i < 100; i++ { 33 | c <- i 34 | } 35 | q <- 1 36 | close(c) 37 | }() 38 | 39 | return c 40 | } 41 | -------------------------------------------------------------------------------- /code_samples_es/001-hello-world/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println("Hello World") 7 | } 8 | -------------------------------------------------------------------------------- /code_samples_es/002-cross-compile/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | ) 7 | 8 | func main() { 9 | fmt.Printf("runtime: %s\narchitecture: %s\n", runtime.GOOS, runtime.GOARCH) 10 | } 11 | -------------------------------------------------------------------------------- /code_samples_es/003-packages/cat/info.go: -------------------------------------------------------------------------------- 1 | package cat 2 | 3 | import "fmt" 4 | 5 | func Hello() { 6 | fmt.Println("Hello from cat") 7 | } 8 | 9 | func Eats() { 10 | fmt.Println("Cat eats birds") 11 | } 12 | -------------------------------------------------------------------------------- /code_samples_es/003-packages/dog/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/003-packages/cat" 6 | ) 7 | 8 | func main() { 9 | fmt.Println("Hello from dog.") 10 | cat.Hello() 11 | cat.Eats() 12 | } 13 | -------------------------------------------------------------------------------- /code_samples_es/004-ninja-level-nine/01-goroutines-waitgroups/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | "sync" 7 | ) 8 | 9 | func main() { 10 | 11 | fmt.Println("begin cpu", runtime.NumCPU()) 12 | fmt.Println("begin gs", runtime.NumGoroutine()) 13 | 14 | var wg sync.WaitGroup 15 | wg.Add(2) 16 | 17 | go func() { 18 | fmt.Println("hello from thing one") 19 | wg.Done() 20 | }() 21 | 22 | go func() { 23 | fmt.Println("hello from thing two") 24 | wg.Done() 25 | }() 26 | 27 | fmt.Println("mid cpu", runtime.NumCPU()) 28 | fmt.Println("mid gs", runtime.NumGoroutine()) 29 | 30 | wg.Wait() 31 | 32 | fmt.Println("about to exit") 33 | fmt.Println("end cpu", runtime.NumCPU()) 34 | fmt.Println("end gs", runtime.NumGoroutine()) 35 | } 36 | -------------------------------------------------------------------------------- /code_samples_es/004-ninja-level-nine/02-methods-sets/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type person struct { 6 | first string 7 | } 8 | 9 | type human interface { 10 | speak() 11 | } 12 | 13 | func (p *person) speak() { 14 | fmt.Println("Hello") 15 | } 16 | 17 | func saySomething(h human) { 18 | h.speak() 19 | } 20 | 21 | func main() { 22 | p1 := person{ 23 | first: "James", 24 | } 25 | 26 | saySomething(&p1) 27 | 28 | // does not work 29 | // saySomething(p1) 30 | 31 | p1.speak() 32 | } 33 | -------------------------------------------------------------------------------- /code_samples_es/004-ninja-level-nine/03-race-condition/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | "sync" 7 | ) 8 | 9 | func main() { 10 | var wg sync.WaitGroup 11 | 12 | incrementer := 0 13 | gs := 100 14 | wg.Add(gs) 15 | 16 | for i := 0; i < gs; i++ { 17 | go func() { 18 | v := incrementer 19 | runtime.Gosched() 20 | v++ 21 | incrementer = v 22 | fmt.Println(incrementer) 23 | wg.Done() 24 | }() 25 | } 26 | wg.Wait() 27 | fmt.Println("end value:", incrementer) 28 | } 29 | -------------------------------------------------------------------------------- /code_samples_es/004-ninja-level-nine/04-mutex/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | ) 7 | 8 | func main() { 9 | var wg sync.WaitGroup 10 | 11 | incrementer := 0 12 | gs := 100 13 | wg.Add(gs) 14 | var m sync.Mutex 15 | 16 | for i := 0; i < gs; i++ { 17 | go func() { 18 | m.Lock() 19 | v := incrementer 20 | v++ 21 | incrementer = v 22 | fmt.Println(incrementer) 23 | m.Unlock() 24 | wg.Done() 25 | }() 26 | } 27 | wg.Wait() 28 | fmt.Println("end value:", incrementer) 29 | } 30 | -------------------------------------------------------------------------------- /code_samples_es/004-ninja-level-nine/05-atomic/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | "sync/atomic" 7 | ) 8 | 9 | func main() { 10 | var wg sync.WaitGroup 11 | var incrementer int64 12 | 13 | gs := 100 14 | wg.Add(gs) 15 | 16 | for i := 0; i < gs; i++ { 17 | go func() { 18 | atomic.AddInt64(&incrementer, 1) 19 | fmt.Println(atomic.LoadInt64(&incrementer)) 20 | wg.Done() 21 | }() 22 | } 23 | wg.Wait() 24 | fmt.Println("end value:", incrementer) 25 | } 26 | -------------------------------------------------------------------------------- /code_samples_es/004-ninja-level-nine/06-os-arch/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(runtime.GOOS, runtime.GOARCH) 10 | } 11 | -------------------------------------------------------------------------------- /code_samples_es/005-channels/01-channels-block/01-does-not-run/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan int) 7 | 8 | c <- 42 9 | 10 | fmt.Println(<-c) 11 | } 12 | -------------------------------------------------------------------------------- /code_samples_es/005-channels/01-channels-block/02-successful-pass-of-value/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan int) 7 | 8 | go func() { 9 | c <- 42 10 | }() 11 | 12 | fmt.Println(<-c) 13 | } 14 | -------------------------------------------------------------------------------- /code_samples_es/005-channels/01-channels-block/03-succesful-buffer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan int, 1) 7 | 8 | c <- 42 9 | 10 | fmt.Println(<-c) 11 | } 12 | -------------------------------------------------------------------------------- /code_samples_es/005-channels/01-channels-block/04-unsuccesful-buffer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan int, 1) 7 | 8 | c <- 42 9 | c <- 43 10 | 11 | fmt.Println(<-c) 12 | } 13 | -------------------------------------------------------------------------------- /code_samples_es/005-channels/01-channels-block/05-succesful-buffer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan int, 2) 7 | 8 | c <- 42 9 | c <- 43 10 | 11 | fmt.Println(<-c) 12 | fmt.Println(<-c) 13 | } 14 | -------------------------------------------------------------------------------- /code_samples_es/005-channels/02-directional-channels/01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan int, 2) 7 | 8 | c <- 42 9 | c <- 43 10 | 11 | fmt.Println(<-c) 12 | fmt.Println(<-c) 13 | fmt.Println("-----") 14 | fmt.Printf("%T\n", c) 15 | } 16 | -------------------------------------------------------------------------------- /code_samples_es/005-channels/02-directional-channels/02-does-not-work/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan<- int, 2) 7 | 8 | c <- 42 9 | c <- 43 10 | 11 | fmt.Println(<-c) 12 | fmt.Println(<-c) 13 | fmt.Println("-----") 14 | fmt.Printf("%T\n", c) 15 | } 16 | -------------------------------------------------------------------------------- /code_samples_es/005-channels/02-directional-channels/03-does-not-work/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(<-chan int, 2) 7 | 8 | c <- 42 9 | c <- 43 10 | 11 | fmt.Println(<-c) 12 | fmt.Println(<-c) 13 | fmt.Println("-----") 14 | fmt.Printf("%T\n", c) 15 | } 16 | -------------------------------------------------------------------------------- /code_samples_es/005-channels/02-directional-channels/04-using-with-funcs/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan int) 7 | 8 | // send 9 | go foo(c) 10 | 11 | // receive 12 | bar(c) 13 | 14 | fmt.Println("about to exit") 15 | } 16 | 17 | // send 18 | func foo(c chan<- int) { 19 | c <- 42 20 | } 21 | 22 | // receive 23 | func bar(c <-chan int) { 24 | fmt.Println(<-c) 25 | } 26 | -------------------------------------------------------------------------------- /code_samples_es/005-channels/02-directional-channels/05-range-close/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | c := make(chan int) 7 | 8 | // send 9 | go func() { 10 | for i := 0; i < 5; i++ { 11 | c <- i 12 | } 13 | close(c) 14 | }() 15 | 16 | // receive 17 | for v := range c { 18 | fmt.Println(v) 19 | } 20 | 21 | fmt.Println("about to exit") 22 | } 23 | -------------------------------------------------------------------------------- /code_samples_es/005-channels/03-select/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | eve := make(chan int) 7 | odd := make(chan int) 8 | quit := make(chan int) 9 | 10 | // send 11 | go send(eve, odd, quit) 12 | 13 | // receive 14 | receive(eve, odd, quit) 15 | 16 | fmt.Println("about to exit") 17 | } 18 | 19 | func receive(e, o, q <-chan int) { 20 | for { 21 | select { 22 | case v := <-e: 23 | fmt.Println("from the eve channel:", v) 24 | case v := <-o: 25 | fmt.Println("from the odd channel:", v) 26 | case v := <-q: 27 | fmt.Println("from the quit channel:", v) 28 | return 29 | } 30 | } 31 | } 32 | 33 | func send(e, o, q chan<- int) { 34 | for i := 0; i < 100; i++ { 35 | if i%2 == 0 { 36 | e <- i 37 | } else { 38 | o <- i 39 | } 40 | } 41 | q <- 0 42 | } 43 | -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/00-check-errors/01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | n, err := fmt.Println("Hello") 7 | if err != nil { 8 | fmt.Println(err) 9 | } 10 | fmt.Println(n) 11 | } 12 | -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/00-check-errors/02/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var answer1, answer2, answer3 string 7 | 8 | fmt.Print("Name: ") 9 | _, err := fmt.Scan(&answer1) 10 | if err != nil { 11 | panic(err) 12 | } 13 | 14 | fmt.Print("Fav Food: ") 15 | _, err = fmt.Scan(&answer2) 16 | if err != nil { 17 | panic(err) 18 | } 19 | 20 | fmt.Print("Fav Sport: ") 21 | _, err = fmt.Scan(&answer3) 22 | if err != nil { 23 | panic(err) 24 | } 25 | 26 | fmt.Println(answer1, answer2, answer3) 27 | 28 | } 29 | -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/00-check-errors/03/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "os" 7 | "strings" 8 | ) 9 | 10 | func main() { 11 | f, err := os.Create("names.txt") 12 | if err != nil { 13 | fmt.Println(err) 14 | return 15 | } 16 | defer f.Close() 17 | 18 | r := strings.NewReader("James Bond") 19 | 20 | io.Copy(f, r) 21 | } 22 | -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/00-check-errors/04/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "os" 7 | ) 8 | 9 | func main() { 10 | f, err := os.Open("names.txt") 11 | if err != nil { 12 | fmt.Println(err) 13 | return 14 | } 15 | defer f.Close() 16 | 17 | bs, err := ioutil.ReadAll(f) 18 | if err != nil { 19 | fmt.Println(err) 20 | return 21 | } 22 | 23 | fmt.Println(string(bs)) 24 | } 25 | -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/00-check-errors/04/names.txt: -------------------------------------------------------------------------------- 1 | James Bond -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/01-fmt-println/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | ) 7 | 8 | func main() { 9 | _, err := os.Open("no-file.txt") 10 | if err != nil { 11 | fmt.Println("err happened", err) 12 | // log.Println("err happened", err) 13 | // log.Fatalln(err) 14 | // panic(err) 15 | } 16 | } 17 | 18 | // Println formats using the default formats for its operands and writes to standard output. 19 | -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/02-log-println/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | ) 7 | 8 | func main() { 9 | _, err := os.Open("no-file.txt") 10 | if err != nil { 11 | // fmt.Println("err happened", err) 12 | log.Println("err happened", err) 13 | // log.Fatalln(err) 14 | // panic(err) 15 | } 16 | } 17 | 18 | /* 19 | Package log implements a simple logging package ... writes to standard error and prints the date and time of each logged message ... 20 | */ 21 | 22 | // log.Println calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Println. 23 | -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/03-log-set-output/log.txt: -------------------------------------------------------------------------------- 1 | 2017/08/07 13:16:32 err happened open no-file.txt: no such file or directory 2 | -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/03-log-set-output/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | ) 8 | 9 | func main() { 10 | f, err := os.Create("log.txt") 11 | if err != nil { 12 | fmt.Println(err) 13 | } 14 | defer f.Close() 15 | log.SetOutput(f) 16 | 17 | f2, err := os.Open("no-file.txt") 18 | if err != nil { 19 | // fmt.Println("err happened", err) 20 | log.Println("err happened", err) 21 | // log.Fatalln(err) 22 | // panic(err) 23 | } 24 | defer f2.Close() 25 | 26 | fmt.Println("check the log.txt file in the directory") 27 | } 28 | 29 | // Println calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Println. 30 | -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/04-log-fatalln/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | ) 8 | 9 | func main() { 10 | defer foo() 11 | _, err := os.Open("no-file.txt") 12 | if err != nil { 13 | // fmt.Println("err happened", err) 14 | // log.Println("err happened", err) 15 | log.Fatalln(err) 16 | // panic(err) 17 | } 18 | } 19 | 20 | func foo() { 21 | fmt.Println("When os.Exit() is called, deferred functions don't run") 22 | } 23 | 24 | /* 25 | ... the Fatal functions call os.Exit(1) after writing the log message ... 26 | */ 27 | 28 | // Fatalln is equivalent to Println() followed by a call to os.Exit(1). 29 | -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/05-log-panic/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | ) 7 | 8 | func main() { 9 | _, err := os.Open("no-file.txt") 10 | if err != nil { 11 | // fmt.Println("err happened", err) 12 | // log.Println("err happened", err) 13 | // log.Fatalln(err) 14 | log.Panicln(err) 15 | // panic(err) 16 | } 17 | } 18 | 19 | /* 20 | Panicln is equivalent to Println() followed by a call to panic(). 21 | */ 22 | 23 | // Fatalln is equivalent to Println() followed by a call to os.Exit(1). 24 | -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/06-panic/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | ) 6 | 7 | func main() { 8 | _, err := os.Open("no-file.txt") 9 | if err != nil { 10 | // fmt.Println("err happened", err) 11 | // log.Println("err happened", err) 12 | // log.Fatalln(err) 13 | // log.Panicln(err) 14 | panic(err) 15 | } 16 | } 17 | 18 | // http://godoc.org/builtin#panic 19 | -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/07-custom-errors/01_errors-new/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "log" 6 | ) 7 | 8 | func main() { 9 | _, err := sqrt(-10) 10 | if err != nil { 11 | log.Fatalln(err) 12 | } 13 | } 14 | 15 | func sqrt(f float64) (float64, error) { 16 | if f < 0 { 17 | return 0, errors.New("norgate math: square root of negative number") 18 | } 19 | return 42, nil 20 | } 21 | -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/07-custom-errors/02_errors-new_var/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "log" 7 | ) 8 | 9 | var ErrNorgateMath = errors.New("norgate math: square root of negative number") 10 | 11 | func main() { 12 | fmt.Printf("%T\n", ErrNorgateMath) 13 | _, err := sqrt(-10) 14 | if err != nil { 15 | log.Fatalln(err) 16 | } 17 | } 18 | 19 | func sqrt(f float64) (float64, error) { 20 | if f < 0 { 21 | return 0, ErrNorgateMath 22 | } 23 | return 42, nil 24 | } 25 | 26 | // see use of errors.New in standard library: 27 | // http://golang.org/src/pkg/bufio/bufio.go 28 | // http://golang.org/src/pkg/io/io.go 29 | -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/07-custom-errors/03_fmt-errorf/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | ) 7 | 8 | func main() { 9 | _, err := sqrt(-10.23) 10 | if err != nil { 11 | log.Fatalln(err) 12 | } 13 | } 14 | 15 | func sqrt(f float64) (float64, error) { 16 | if f < 0 { 17 | return 0, fmt.Errorf("norgate math again: square root of negative number: %v", f) 18 | } 19 | return 42, nil 20 | } 21 | -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/07-custom-errors/04_fmt-errorf_var/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | ) 7 | 8 | func main() { 9 | _, err := sqrt(-10.23) 10 | if err != nil { 11 | log.Fatalln(err) 12 | } 13 | } 14 | 15 | func sqrt(f float64) (float64, error) { 16 | if f < 0 { 17 | ErrNorgateMath := fmt.Errorf("norgate math again: square root of negative number: %v", f) 18 | return 0, ErrNorgateMath 19 | } 20 | return 42, nil 21 | } 22 | -------------------------------------------------------------------------------- /code_samples_es/006-error-handling/07-custom-errors/05_custom-type/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | ) 7 | 8 | type norgateMathError struct { 9 | lat string 10 | long string 11 | err error 12 | } 13 | 14 | func (n norgateMathError) Error() string { 15 | return fmt.Sprintf("a norgate math error occured: %v %v %v", n.lat, n.long, n.err) 16 | } 17 | 18 | func main() { 19 | _, err := sqrt(-10.23) 20 | if err != nil { 21 | log.Println(err) 22 | } 23 | } 24 | 25 | func sqrt(f float64) (float64, error) { 26 | if f < 0 { 27 | nme := fmt.Errorf("norgate math redux: square root of negative number: %v", f) 28 | return 0, norgateMathError{"50.2289 N", "99.4656 W", nme} 29 | } 30 | return 42, nil 31 | } 32 | 33 | // see use of structs with error type in standard library: 34 | // 35 | // http://golang.org/pkg/net/#OpError 36 | // http://golang.org/src/pkg/net/dial.go 37 | // http://golang.org/src/pkg/net/net.go 38 | // 39 | // http://golang.org/src/pkg/encoding/json/decode.go 40 | -------------------------------------------------------------------------------- /code_samples_es/007-documentation/01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/007-documentation/01/mymath" 6 | ) 7 | 8 | func main() { 9 | fmt.Println("2 + 3 =", mymath.Sum(2, 3)) 10 | fmt.Println("4 + 7 =", mymath.Sum(4, 7)) 11 | fmt.Println("5 + 9 =", mymath.Sum(5, 9)) 12 | } 13 | -------------------------------------------------------------------------------- /code_samples_es/007-documentation/01/mymath/main.go: -------------------------------------------------------------------------------- 1 | // Package mymath provides ACME inc math solutions. 2 | package mymath 3 | 4 | // Sum adds an unlimited number of values of type int. 5 | func Sum(xi ...int) int { 6 | sum := 0 7 | for _, v := range xi { 8 | sum += v 9 | } 10 | return sum 11 | } 12 | -------------------------------------------------------------------------------- /code_samples_es/008-ninja-level-twelve/01/dog/main.go: -------------------------------------------------------------------------------- 1 | // Package dog allows us to more fully understand dogs. 2 | package dog 3 | 4 | // Years converts human years to dog years. 5 | func Years(n int) int { 6 | return n * 7 7 | } 8 | -------------------------------------------------------------------------------- /code_samples_es/008-ninja-level-twelve/01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/008-ninja-level-twelve/01/dog" 6 | ) 7 | 8 | type canine struct { 9 | name string 10 | age int 11 | } 12 | 13 | func main() { 14 | fido := canine{ 15 | name: "Fido", 16 | age: dog.Years(10), 17 | } 18 | fmt.Println(fido) 19 | } 20 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/01-test/01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println("2 + 3 =", mySum(2, 3)) 7 | fmt.Println("4 + 7 =", mySum(4, 7)) 8 | fmt.Println("5 + 9 =", mySum(5, 9)) 9 | } 10 | 11 | func mySum(xi ...int) int { 12 | sum := 0 13 | for _, v := range xi { 14 | sum += v 15 | } 16 | return sum 17 | } 18 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/01-test/01/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "testing" 4 | 5 | func TestMySum(t *testing.T) { 6 | x := mySum(2, 3) 7 | if x != 5 { 8 | t.Error("Expected", 5, "Got", x) 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/01-test/02/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println("2 + 3 =", myAdd(2, 3)) 7 | fmt.Println("5 + 7 =", myAdd(5, 7)) 8 | } 9 | 10 | func myAdd(xi ...int) int { 11 | var sum int 12 | for _, v := range xi { 13 | sum += v 14 | } 15 | return sum 16 | } 17 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/01-test/02/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "testing" 4 | 5 | func TestMyAdd(t *testing.T) { 6 | if myAdd(2, 3) != 2+3 { 7 | t.Error("Expected", 5, "Got", myAdd(2, 3)) 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/02-table-test/01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println("2 + 3 =", mySum(2, 3)) 7 | fmt.Println("4 + 7 =", mySum(4, 7)) 8 | fmt.Println("5 + 9 =", mySum(5, 9)) 9 | } 10 | 11 | func mySum(xi ...int) int { 12 | sum := 0 13 | for _, v := range xi { 14 | sum += v 15 | } 16 | return sum 17 | } 18 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/02-table-test/01/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "testing" 4 | 5 | func TestMySum(t *testing.T) { 6 | 7 | type test struct { 8 | data []int 9 | answer int 10 | } 11 | 12 | tests := []test{ 13 | test{[]int{21, 21}, 42}, 14 | test{[]int{3, 4, 5}, 12}, 15 | test{[]int{1, 1}, 2}, 16 | test{[]int{-1, 0, 1}, 0}, 17 | } 18 | 19 | for _, v := range tests { 20 | x := mySum(v.data...) 21 | if x != v.answer { 22 | t.Error("Expected", v.answer, "Got", x) 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/02-table-test/02/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println("2 + 3 =", myAdd(2, 3)) 7 | fmt.Println("5 + 7 =", myAdd(5, 7)) 8 | } 9 | 10 | func myAdd(xi ...int) int { 11 | var sum int 12 | for _, v := range xi { 13 | sum += v 14 | } 15 | return sum 16 | } 17 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/02-table-test/02/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "testing" 4 | 5 | func TestMyAdd(t *testing.T) { 6 | type test struct { 7 | data []int 8 | answer int 9 | } 10 | 11 | tests := []test{ 12 | test{[]int{2, 3, 4}, 9}, 13 | test{[]int{42, 43, 44}, 129}, 14 | test{[]int{5, 7}, 12}, 15 | test{[]int{7, 7, 7}, 21}, 16 | test{[]int{14, 18}, 32}, 17 | test{[]int{12, 19}, 31}, 18 | test{[]int{1, 1}, 2}, 19 | } 20 | 21 | for _, v := range tests { 22 | x := myAdd(v.data...) 23 | if x != v.answer { 24 | t.Error("Expected", v.answer, "Got", x) 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/03-examples/01/acdc/main.go: -------------------------------------------------------------------------------- 1 | // Package acdc asks if you are ready to rock 2 | package acdc 3 | 4 | // Sum adds an unlimited number of values of type int 5 | func Sum(xi ...int) int { 6 | s := 0 7 | for _, v := range xi { 8 | s += v 9 | } 10 | return s 11 | } 12 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/03-examples/01/acdc/main_test.go: -------------------------------------------------------------------------------- 1 | package acdc 2 | 3 | import "fmt" 4 | 5 | func ExampleSum() { 6 | fmt.Println(Sum(2, 3)) 7 | // Output: 8 | // 5 9 | } 10 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/03-examples/01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/009-testing/03-examples/01/acdc" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(acdc.Sum(2, 3)) 10 | fmt.Println(acdc.Sum(2, 3, 4, 5, 6, 7, 8, 9)) 11 | } 12 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/03-examples/02/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/007-documentation/01/mymath" 6 | ) 7 | 8 | func main() { 9 | fmt.Println("2 + 3 =", mymath.Sum(2, 3)) 10 | fmt.Println("4 + 7 =", mymath.Sum(4, 7)) 11 | fmt.Println("5 + 9 =", mymath.Sum(5, 9)) 12 | } 13 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/03-examples/02/mymathtwo/main.go: -------------------------------------------------------------------------------- 1 | // Package mymathtwo provides ACME inc math solutions. 2 | package mymathtwo 3 | 4 | // Sum adds an unlimited number of values of type int. 5 | func Sum(xi ...int) int { 6 | sum := 0 7 | for _, v := range xi { 8 | sum += v 9 | } 10 | return sum 11 | } 12 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/03-examples/02/mymathtwo/main_test.go: -------------------------------------------------------------------------------- 1 | package mymathtwo 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/007-documentation/01/mymath" 6 | "testing" 7 | ) 8 | 9 | func TestSum(t *testing.T) { 10 | 11 | type test struct { 12 | data []int 13 | answer int 14 | } 15 | 16 | tests := []test{ 17 | test{[]int{21, 21}, 42}, 18 | test{[]int{3, 4, 5}, 12}, 19 | test{[]int{1, 1}, 2}, 20 | test{[]int{-1, 0, 1}, 0}, 21 | } 22 | 23 | for _, v := range tests { 24 | x := Sum(v.data...) 25 | if x != v.answer { 26 | t.Error("Expected", v.answer, "Got", x) 27 | } 28 | } 29 | } 30 | 31 | func ExampleSum() { 32 | fmt.Println(Sum(2, 3)) 33 | // Output: 34 | // 5 35 | } 36 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/04-benchmark/00-live/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/009-testing/04-benchmark/00-live/saying" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(saying.Greet("James")) 10 | } 11 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/04-benchmark/00-live/saying/c.out: -------------------------------------------------------------------------------- 1 | mode: set 2 | github.com/GoesToEleven/go-programming/code_samples/009-testing/04-benchmark/00-live/saying/main.go:5.29,7.2 1 1 3 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/04-benchmark/00-live/saying/main.go: -------------------------------------------------------------------------------- 1 | package saying 2 | 3 | import "fmt" 4 | 5 | func Greet(s string) string { 6 | return fmt.Sprint("Welcome my dear ", s) 7 | } 8 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/04-benchmark/00-live/saying/main_test.go: -------------------------------------------------------------------------------- 1 | package saying 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestGreet(t *testing.T) { 9 | s := Greet("James") 10 | if s != "Welcome my dear James" { 11 | t.Error("got", s, "expected", "Welcome my dear James") 12 | } 13 | } 14 | 15 | func ExampleGreet() { 16 | fmt.Println(Greet("James")) 17 | // Output: 18 | // Welcome my dear James 19 | } 20 | 21 | func BenchmarkGreet(b *testing.B) { 22 | for i := 0; i < b.N; i++ { 23 | Greet("James") 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/04-benchmark/01-greet/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(Greet("James")) 7 | } 8 | 9 | func Greet(s string) string { 10 | return fmt.Sprint("Hello my dear, ", s) 11 | } 12 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/04-benchmark/01-greet/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestGreet(t *testing.T) { 8 | s := Greet("James") 9 | if s != "Hello my dear, James" { 10 | t.Error("got", s, "want", "Hello my dear, James") 11 | } 12 | } 13 | 14 | func BenchmarkGreet(b *testing.B) { 15 | for i := 0; i < b.N; i++ { 16 | Greet("James") 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/04-benchmark/02-greet/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/009-testing/04-benchmark/02-greet/mystr" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(mystr.Greet("James")) 10 | } 11 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/04-benchmark/02-greet/mystr/main.go: -------------------------------------------------------------------------------- 1 | package mystr 2 | 3 | import "fmt" 4 | 5 | func Greet(s string) string { 6 | return fmt.Sprint("Hello my dear, ", s) 7 | } 8 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/04-benchmark/02-greet/mystr/main_test.go: -------------------------------------------------------------------------------- 1 | package mystr 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestGreet(t *testing.T) { 9 | s := Greet("James") 10 | if s != "Hello my dear, James" { 11 | t.Error("got", s, "want", "Hello my dear, James") 12 | } 13 | } 14 | 15 | func ExampleGreet() { 16 | fmt.Println(Greet("James")) 17 | // Output: 18 | // Hello my dear, James 19 | } 20 | 21 | func BenchmarkGreet(b *testing.B) { 22 | for i := 0; i < b.N; i++ { 23 | Greet("James") 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/04-benchmark/03-cat/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/009-testing/04-benchmark/03-cat/mystr" 6 | "strings" 7 | ) 8 | 9 | const s = "We ask ourselves, Who am I to be brilliant, gorgeous, talented, fabulous? Actually, who are you not to be? Your playing small does not serve the world. There is nothing enlightened about shrinking so that other people won't feel insecure around you. We are all meant to shine, as children do. We were born to make manifest the glory that is within us. It's not just in some of us; it's in everyone. And as we let our own light shine, we unconsciously give other people permission to do the same. As we are liberated from our own fear, our presence automatically liberates others. - Marianne Williamson" 10 | 11 | func main() { 12 | 13 | xs := strings.Split(s, " ") 14 | 15 | for _, v := range xs { 16 | fmt.Println(v) 17 | } 18 | 19 | fmt.Printf("\n%s\n", mystr.Cat(xs)) 20 | fmt.Printf("\n%s\n\n", mystr.Join(xs)) 21 | } 22 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/04-benchmark/03-cat/mystr/main.go: -------------------------------------------------------------------------------- 1 | package mystr 2 | 3 | import "strings" 4 | 5 | func Cat(xs []string) string { 6 | s := xs[0] 7 | for _, v := range xs[1:] { 8 | s += " " 9 | s += v 10 | } 11 | return s 12 | } 13 | 14 | func Join(xs []string) string { 15 | return strings.Join(xs, " ") 16 | } 17 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/04-benchmark/03-cat/mystr/main_test.go: -------------------------------------------------------------------------------- 1 | package mystr 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | "testing" 7 | ) 8 | 9 | func TestCat(t *testing.T) { 10 | s := "Shaken not stirred" 11 | xs := strings.Split(s, " ") 12 | s = Cat(xs) 13 | if s != "Shaken not stirred" { 14 | t.Error("got", s, "want", "Shaken not stirred") 15 | } 16 | } 17 | 18 | func TestJoin(t *testing.T) { 19 | s := "Shaken not stirred" 20 | xs := strings.Split(s, " ") 21 | s = Join(xs) 22 | if s != "Shaken not stirred" { 23 | t.Error("got", s, "want", "Shaken not stirred") 24 | } 25 | } 26 | 27 | func ExampleCat() { 28 | s := "Shaken not stirred" 29 | xs := strings.Split(s, " ") 30 | fmt.Println(Cat(xs)) 31 | // Output: 32 | // Shaken not stirred 33 | } 34 | 35 | func ExampleJoin() { 36 | s := "Shaken not stirred" 37 | xs := strings.Split(s, " ") 38 | fmt.Println(Join(xs)) 39 | // Output: 40 | // Shaken not stirred 41 | } 42 | 43 | const s = "We ask ourselves, Who am I to be brilliant, gorgeous, talented, fabulous? Actually, who are you not to be? Your playing small does not serve the world. There is nothing enlightened about shrinking so that other people won't feel insecure around you. We are all meant to shine, as children do. We were born to make manifest the glory that is within us. It's not just in some of us; it's in everyone. And as we let our own light shine, we unconsciously give other people permission to do the same. As we are liberated from our own fear, our presence automatically liberates others. - Marianne Williamson" 44 | 45 | var xs []string 46 | 47 | func BenchmarkCat(b *testing.B) { 48 | xs = strings.Split(s, " ") 49 | b.ResetTimer() 50 | for i := 0; i < b.N; i++ { 51 | Cat(xs) 52 | } 53 | } 54 | 55 | func BenchmarkJoin(b *testing.B) { 56 | xs = strings.Split(s, " ") 57 | b.ResetTimer() 58 | for i := 0; i < b.N; i++ { 59 | Join(xs) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /code_samples_es/009-testing/04-benchmark/readme.md: -------------------------------------------------------------------------------- 1 | # Remember to BET 2 | - Benchmark 3 | - Example 4 | - Test 5 | 6 | ``` 7 | BenchmarkCat(b *testing.B) 8 | ExampleCat() 9 | TestCat(t *testing.T) 10 | ``` 11 | 12 | # Commands 13 | 14 | ``` 15 | godoc -http=:8080 16 | 17 | go test 18 | go test -bench . 19 | go test -cover 20 | go test -coverprofile c.out 21 | go tool cover -html=c.out 22 | ``` 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/01/finished/dog/c.out: -------------------------------------------------------------------------------- 1 | mode: set 2 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/01/finished/dog/main.go:5.23,7.2 1 1 3 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/01/finished/dog/main.go:10.26,12.25 2 1 4 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/01/finished/dog/main.go:15.2,15.14 1 1 5 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/01/finished/dog/main.go:12.25,14.3 1 1 6 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/01/finished/dog/main.go: -------------------------------------------------------------------------------- 1 | // Package dog allows us to more fully understand dogs. 2 | package dog 3 | 4 | // Years converts human years to dog years. 5 | func Years(n int) int { 6 | return n * 7 7 | } 8 | 9 | // YearsTwo converts human years to dog years. 10 | func YearsTwo(n int) int { 11 | count := 0 12 | for i := 0; i < n; i++ { 13 | count += 7 14 | } 15 | return count 16 | } 17 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/01/finished/dog/main_test.go: -------------------------------------------------------------------------------- 1 | package dog 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestYears(t *testing.T) { 9 | n := Years(10) 10 | if n != 70 { 11 | t.Error("got", n, "want", 70) 12 | } 13 | } 14 | 15 | func TestYearsTwo(t *testing.T) { 16 | n := YearsTwo(10) 17 | if n != 70 { 18 | t.Error("got", n, "want", 70) 19 | } 20 | } 21 | 22 | func ExampleYears() { 23 | fmt.Println(Years(10)) 24 | // Output: 25 | // 70 26 | } 27 | 28 | func ExampleYearsTwo() { 29 | fmt.Println(YearsTwo(10)) 30 | // Output: 31 | // 70 32 | } 33 | 34 | func BenchmarkYears(b *testing.B) { 35 | for i := 0; i < b.N; i++ { 36 | Years(10) 37 | } 38 | } 39 | 40 | func BenchmarkYearsTwo(b *testing.B) { 41 | for i := 0; i < b.N; i++ { 42 | YearsTwo(10) 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/01/finished/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/01/starting-code/dog" 6 | ) 7 | 8 | type canine struct { 9 | name string 10 | age int 11 | } 12 | 13 | func main() { 14 | fido := canine{ 15 | name: "Fido", 16 | age: dog.Years(10), 17 | } 18 | fmt.Println(fido) 19 | fmt.Println(dog.YearsTwo(20)) 20 | } 21 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/01/starting-code/dog/main.go: -------------------------------------------------------------------------------- 1 | // Package dog allows us to more fully understand dogs. 2 | package dog 3 | 4 | // Years converts human years to dog years. 5 | func Years(n int) int { 6 | return n * 7 7 | } 8 | 9 | // YearsTwo converts human years to dog years. 10 | func YearsTwo(n int) int { 11 | count := 0 12 | for i := 0; i < n; i++ { 13 | count += 7 14 | } 15 | return count 16 | } 17 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/01/starting-code/main.go: -------------------------------------------------------------------------------- 1 | package starting_code 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/01/starting-code/dog" 6 | ) 7 | 8 | type canine struct { 9 | name string 10 | age int 11 | } 12 | 13 | func main() { 14 | fido := canine{ 15 | name: "Fido", 16 | age: dog.Years(10), 17 | } 18 | fmt.Println(fido) 19 | fmt.Println(dog.YearsTwo(20)) 20 | } 21 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/02/01-code-starting/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/01-code-starting/quote" 6 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/01-code-starting/word" 7 | ) 8 | 9 | func main() { 10 | fmt.Println(word.Count(quote.SunAlso)) 11 | 12 | for k, v := range word.UseCount(quote.SunAlso) { 13 | fmt.Println(v, k) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/02/01-code-starting/word/main.go: -------------------------------------------------------------------------------- 1 | package word 2 | 3 | import "strings" 4 | 5 | // no need to write an example for this one 6 | // writing a test for this one is a bonus challenge; harder 7 | func UseCount(s string) map[string]int { 8 | xs := strings.Fields(s) 9 | m := make(map[string]int) 10 | for _, v := range xs { 11 | m[v]++ 12 | } 13 | return m 14 | } 15 | 16 | func Count(s string) int { 17 | // write the code for this func 18 | } 19 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/02/02-code-finished/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/02-code-finished/quote" 6 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/02-code-finished/word" 7 | ) 8 | 9 | func main() { 10 | fmt.Println(word.Count(quote.SunAlso)) 11 | 12 | for k, v := range word.UseCount(quote.SunAlso) { 13 | fmt.Println(v, k) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/02/02-code-finished/word/c.out: -------------------------------------------------------------------------------- 1 | mode: set 2 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/02-code-finished/word/main.go:7.40,10.23 3 1 3 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/02-code-finished/word/main.go:13.2,13.10 1 1 4 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/02-code-finished/word/main.go:10.23,12.3 1 1 5 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/02-code-finished/word/main.go:17.26,20.2 2 1 6 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/02/02-code-finished/word/main.go: -------------------------------------------------------------------------------- 1 | // Package word provides custom functions for working with strings and words. 2 | package word 3 | 4 | import "strings" 5 | 6 | // UseCount returns the number of times each word is used in a string. 7 | func UseCount(s string) map[string]int { 8 | xs := strings.Fields(s) 9 | m := make(map[string]int) 10 | for _, v := range xs { 11 | m[v]++ 12 | } 13 | return m 14 | } 15 | 16 | // Count returns the number of words in a string. 17 | func Count(s string) int { 18 | xs := strings.Fields(s) 19 | return len(xs) 20 | } 21 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/02/02-code-finished/word/main_test.go: -------------------------------------------------------------------------------- 1 | package word 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/02/02-code-finished/quote" 6 | "testing" 7 | ) 8 | 9 | func TestUseCount(t *testing.T) { 10 | m := UseCount("one two three three three") 11 | for k, v := range m { 12 | switch k { 13 | case "one": 14 | if v != 1 { 15 | t.Error("got", v, "want", 1) 16 | } 17 | case "two": 18 | if v != 1 { 19 | t.Error("got", v, "want", 1) 20 | } 21 | case "three": 22 | if v != 3 { 23 | t.Error("got", v, "want", 1) 24 | } 25 | } 26 | } 27 | } 28 | 29 | func TestCount(t *testing.T) { 30 | n := Count("one two three") 31 | if n != 3 { 32 | t.Error("got", n, "want", 3) 33 | } 34 | } 35 | 36 | func ExampleCount() { 37 | fmt.Println(Count("one two three")) 38 | // Output: 39 | // 3 40 | } 41 | 42 | func BenchmarkCount(b *testing.B) { 43 | for i := 0; i < b.N; i++ { 44 | Count(quote.SunAlso) 45 | } 46 | } 47 | 48 | func BenchmarkUseCount(b *testing.B) { 49 | for i := 0; i < b.N; i++ { 50 | UseCount(quote.SunAlso) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/03/01-code-starting/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/03/01-code-starting/mymath" 6 | ) 7 | 8 | func main() { 9 | xxi := gen() 10 | for _, v := range xxi { 11 | fmt.Println(mymath.CenteredAvg(v)) 12 | } 13 | } 14 | 15 | func gen() [][]int { 16 | a := []int{1, 4, 6, 8, 100} 17 | b := []int{0, 8, 10, 1000} 18 | c := []int{9000, 4, 10, 8, 6, 12} 19 | d := []int{123, 744, 140, 200} 20 | e := [][]int{a, b, c, d} 21 | return e 22 | } 23 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/03/01-code-starting/mymath/main.go: -------------------------------------------------------------------------------- 1 | package mymath 2 | 3 | import "sort" 4 | 5 | // CenteredAvg computes the average of a list of numbers 6 | // after removing the largest and smallest values. 7 | func CenteredAvg(xi []int) float64 { 8 | sort.Ints(xi) 9 | xi = xi[1:(len(xi) - 1)] 10 | 11 | n := 0 12 | for _, v := range xi { 13 | n += v 14 | } 15 | 16 | f := float64(n) / float64(len(xi)) 17 | return f 18 | } 19 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/03/02-code-finished/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/03/02-code-finished/mymath" 6 | ) 7 | 8 | func main() { 9 | xxi := gen() 10 | for _, v := range xxi { 11 | fmt.Println(mymath.CenteredAvg(v)) 12 | } 13 | } 14 | 15 | // gen generates data to pass into CenteredAvg 16 | func gen() [][]int { 17 | a := []int{1, 4, 6, 8, 100} 18 | b := []int{0, 8, 10, 1000} 19 | c := []int{9000, 4, 10, 8, 6, 12} 20 | d := []int{123, 744, 140, 200} 21 | e := [][]int{a, b, c, d} 22 | return e 23 | } 24 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/03/02-code-finished/mymath/c.out: -------------------------------------------------------------------------------- 1 | mode: set 2 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/03/02-code-finished/mymath/main.go:8.36,13.23 4 1 3 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/03/02-code-finished/mymath/main.go:17.2,18.10 2 1 4 | github.com/GoesToEleven/go-programming/code_samples/010-ninja-level-thirteen/03/02-code-finished/mymath/main.go:13.23,15.3 1 1 5 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/03/02-code-finished/mymath/main.go: -------------------------------------------------------------------------------- 1 | // Package mymath provides math solutions relevant to our company. 2 | package mymath 3 | 4 | import "sort" 5 | 6 | // CenteredAvg computes the average of a list of numbers 7 | // after removing the largest and smallest values. 8 | func CenteredAvg(xi []int) float64 { 9 | sort.Ints(xi) 10 | xi = xi[1:(len(xi) - 1)] 11 | 12 | n := 0 13 | for _, v := range xi { 14 | n += v 15 | } 16 | 17 | f := float64(n) / float64(len(xi)) 18 | return f 19 | } 20 | -------------------------------------------------------------------------------- /code_samples_es/010-ninja-level-thirteen/03/02-code-finished/mymath/main_test.go: -------------------------------------------------------------------------------- 1 | package mymath 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestCenteredAvg(t *testing.T) { 9 | type test struct { 10 | data []int 11 | answer float64 12 | } 13 | 14 | tests := []test{ 15 | test{[]int{10, 20, 40, 60, 80}, 40}, 16 | test{[]int{2, 4, 6, 8, 10, 12}, 7}, 17 | test{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9}, 5}, 18 | } 19 | 20 | for _, v := range tests { 21 | f := CenteredAvg(v.data) 22 | if f != v.answer { 23 | t.Error("got", f, "want", v.answer) 24 | } 25 | } 26 | 27 | } 28 | 29 | func ExampleCenteredAvg() { 30 | fmt.Println(CenteredAvg([]int{1, 2, 4, 6, 9})) 31 | // Output: 32 | // 4 33 | } 34 | 35 | func BenchmarkCenteredAvg(b *testing.B) { 36 | for i := 0; i < b.N; i++ { 37 | CenteredAvg([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10000}) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/01-file/01-open/01-ioutil-readall/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "log" 7 | "os" 8 | ) 9 | 10 | func main() { 11 | f, err := os.Open("rumi.txt") 12 | if err != nil { 13 | log.Fatalf("error opening file: %v", err) 14 | } 15 | defer f.Close() 16 | 17 | bs, err := ioutil.ReadAll(f) 18 | if err != nil { 19 | log.Fatalf("error reading file: %v", err) 20 | } 21 | 22 | fmt.Println(string(bs)) 23 | } 24 | -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/01-file/01-open/01-ioutil-readall/rumi.txt: -------------------------------------------------------------------------------- 1 | Do you know what you are? 2 | You are a manuscript oƒ a divine letter. 3 | You are a mirror reflecting a noble face. 4 | This universe is not outside of you. 5 | Look inside yourself; 6 | everything that you want, 7 | you are already that. -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/01-file/01-open/02-bufio-newscanner/dalia-shevin.txt: -------------------------------------------------------------------------------- 1 | I will find myself waist deep in high summer grass. 2 | The humming shock of the golden light. 3 | And I will hear them before I see them and know right away who is bounding across the field to meet me. 4 | All my good dogs will come then, their wet noses bumping against my palms, their hot panting, their rough faithful tongues. 5 | Their eyes young and shiny again. 6 | The wiry scruff of their fur, the unspeakable softness of their bellies, their velvet ears against my cheeks. 7 | I will bend to them, my face covered with their kisses, my hands full of them. 8 | In the grass I will let them knock me down. -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/01-file/01-open/02-bufio-newscanner/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "strings" 9 | ) 10 | 11 | func main() { 12 | f, err := os.Open("dalia-shevin.txt") 13 | if err != nil { 14 | log.Fatalf("error opening file: %v", err) 15 | } 16 | defer f.Close() 17 | 18 | scanner := bufio.NewScanner(f) 19 | for scanner.Scan() { 20 | line := scanner.Text() 21 | if len(line) > 0 { 22 | fmt.Println(strings.ToUpper(line)) 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/01-file/02-newfile/01-write/dog-poem.txt: -------------------------------------------------------------------------------- 1 | If you can sit quietly after difficult news, If in financial down-times you can remain perfectly calm, If you can love unconditionally and see your neighbours travel to fantastic places without a twinge of jealously, If you can happily eat whatever is put on your plate, And if you can fall asleep after a day of running around without a drink or a pill, If you can always find contentment wherever you are, You are probably a dog. -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/01-file/02-newfile/01-write/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io/ioutil" 5 | "log" 6 | "os" 7 | ) 8 | 9 | func main() { 10 | f, err := os.Open("dog-poem.txt") 11 | if err != nil { 12 | log.Fatalf("error opening file: %v", err) 13 | } 14 | defer f.Close() 15 | 16 | bs, err := ioutil.ReadAll(f) 17 | if err != nil { 18 | log.Fatalf("error reading file: %v", err) 19 | } 20 | 21 | nf, err := os.Create("newFile.txt") 22 | if err != nil { 23 | log.Fatalf("error creating file: %v", err) 24 | } 25 | defer nf.Close() 26 | 27 | _, err = nf.Write(bs) 28 | if err != nil { 29 | log.Fatalf("error writing file: %v", err) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/01-file/02-newfile/02-copy/01/dog-poem.txt: -------------------------------------------------------------------------------- 1 | If you can sit quietly after difficult news, If in financial down-times you can remain perfectly calm, If you can love unconditionally and see your neighbours travel to fantastic places without a twinge of jealously, If you can happily eat whatever is put on your plate, And if you can fall asleep after a day of running around without a drink or a pill, If you can always find contentment wherever you are, You are probably a dog. -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/01-file/02-newfile/02-copy/01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io" 5 | "io/ioutil" 6 | "log" 7 | "os" 8 | ) 9 | 10 | func main() { 11 | f, err := os.Open("dog-poem.txt") 12 | if err != nil { 13 | log.Fatalf("error opening file: %v", err) 14 | } 15 | defer f.Close() 16 | 17 | bs, err := ioutil.ReadAll(f) 18 | if err != nil { 19 | log.Fatalf("error reading file: %v", err) 20 | } 21 | 22 | nf, err := os.Create("newFile.txt") 23 | if err != nil { 24 | log.Fatalf("error creating file: %v", err) 25 | } 26 | defer nf.Close() 27 | 28 | _, err = io.Copy(nf, f) 29 | if err != nil { 30 | log.Fatalf("error copying file: %v", err) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/01-file/02-newfile/02-copy/02-strings-newreader/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io" 5 | "io/ioutil" 6 | "log" 7 | "os" 8 | "strings" 9 | ) 10 | 11 | func main() { 12 | nf, err := os.Create("newFile.txt") 13 | if err != nil { 14 | log.Fatalf("error creating file: %v", err) 15 | } 16 | defer nf.Close() 17 | 18 | s := ` 19 | Don’t surrender your loneliness So quickly. 20 | Let it cut more deep. Let it ferment and season you 21 | as few human or even divine ingredients can. 22 | - Hafiz 23 | ` 24 | 25 | rdr := strings.NewReader(s) 26 | 27 | _, err = io.Copy(nf, rdr) 28 | if err != nil { 29 | log.Fatalf("error copying to file: %v", err) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/02-donovan-kernighan/02-structure/01-fibonacci/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/GoesToEleven/go-programming/code_samples/011-code-samples/02-donovan-kernighan/02-structure/01-fibonacci/mymath" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(mymath.Fib(0)) 10 | fmt.Println(mymath.Fib(1)) 11 | fmt.Println(mymath.Fib(2)) 12 | fmt.Println(mymath.Fib(3)) 13 | fmt.Println(mymath.Fib(4)) 14 | fmt.Println(mymath.Fib(5)) 15 | fmt.Println(mymath.Fib(6)) 16 | fmt.Println(mymath.Fib(7)) 17 | fmt.Println(mymath.Fib(8)) 18 | } 19 | -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/02-donovan-kernighan/02-structure/01-fibonacci/mymath/mymath.go: -------------------------------------------------------------------------------- 1 | package mymath 2 | 3 | // Fib returns the nth number in the Fibonacci sequence. 4 | // Fibonacci sequence adds up the previous two numbers: 5 | // 0 1 1 2 3 5 8 13 21 6 | func Fib(n int) int { 7 | x, y := 0, 1 8 | for i := 0; i < n; i++ { 9 | x, y = y, x+y 10 | } 11 | return x 12 | } 13 | -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/02-donovan-kernighan/02-structure/01-fibonacci/mymath/mymath_test.go: -------------------------------------------------------------------------------- 1 | package mymath 2 | 3 | import "testing" 4 | 5 | // Fibonacci sequence adds up the previous two numbers: 6 | // 0 1 1 2 3 5 8 13 21 7 | func TestFib(t *testing.T) { 8 | tests := []struct { 9 | input int 10 | want int 11 | }{ 12 | {0, 0}, 13 | {1, 1}, 14 | {2, 1}, 15 | {3, 2}, 16 | {4, 3}, 17 | {5, 5}, 18 | {6, 8}, 19 | {7, 13}, 20 | {8, 21}, 21 | } 22 | 23 | for _, test := range tests { 24 | if got := Fib(test.input); got != test.want { 25 | t.Errorf(`got Fib(%d) = %d wanted %d`, test.input, got, test.want) 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/02-donovan-kernighan/02-structure/02-celsius-farenheit/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/02-donovan-kernighan/02-structure/02-celsius-farenheit/tempconv/tempconv.go: -------------------------------------------------------------------------------- 1 | // Package tempconv performs Celsius and Fahrenheit temperature computations. 2 | package tempconv 3 | 4 | type Celsius float64 5 | type Fahrenheit float64 6 | 7 | const ( 8 | AbsoluteZeroC Celsius = -273.15 9 | FreezingC Celsius = 0 10 | BoilingC Celsius = 100 11 | ) 12 | 13 | func CToF(c Celsius) Fahrenheit { 14 | return Fahrenheit(c*9/5 + 32) 15 | } 16 | 17 | func FToC(f Fahrenheit) Celsius { 18 | return Celsius((f - 32) * 5 / 9) 19 | } 20 | -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/02-donovan-kernighan/02-structure/02-celsius-farenheit/tempconv/tempconv_test.go: -------------------------------------------------------------------------------- 1 | package tempconv 2 | -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/02-donovan-kernighan/11-testing/01/word/word.go: -------------------------------------------------------------------------------- 1 | // Package word provides utilities for word games. 2 | package word 3 | 4 | // IsPalidrome reports whether s reads the same forward and backward. 5 | func IsPalindrome(s string) bool { 6 | for i := range s { 7 | if s[i] != s[(len(s)-1)-i] { 8 | return false 9 | } 10 | } 11 | return true 12 | } 13 | -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/02-donovan-kernighan/11-testing/01/word/word_test.go: -------------------------------------------------------------------------------- 1 | package word 2 | 3 | import "testing" 4 | 5 | func TestIsPalindrome(t *testing.T) { 6 | if !IsPalindrome("mom") { 7 | t.Error(`IsPalindrome("mom") = false`) 8 | } 9 | if !IsPalindrome("kayak") { 10 | t.Error(`IsPalindrome("kayak") = false`) 11 | } 12 | } 13 | 14 | func TestNonPalindrome(t *testing.T) { 15 | if IsPalindrome("dog") { 16 | t.Error(`IsPalindrone("dog") = true`) 17 | } 18 | } 19 | 20 | func TestFrenchPalindrone(t *testing.T) { 21 | s := "été" 22 | if !IsPalindrome(s) { 23 | t.Errorf(`IsPalindrone(%q) = false`, s) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/02-donovan-kernighan/11-testing/02/word/word.go: -------------------------------------------------------------------------------- 1 | // Package word provides utilities for word games. 2 | package word 3 | 4 | import "unicode" 5 | 6 | // IsPalidrome reports whether s reads the same forward and backward. 7 | func IsPalindrome(s string) bool { 8 | var letters []rune 9 | for _, r := range s { 10 | if unicode.IsLetter(r) { 11 | letters = append(letters, unicode.ToLower(r)) 12 | } 13 | } 14 | for i := range letters { 15 | if letters[i] != letters[(len(letters)-1)-i] { 16 | return false 17 | } 18 | } 19 | return true 20 | } 21 | -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/02-donovan-kernighan/11-testing/02/word/word_test.go: -------------------------------------------------------------------------------- 1 | package word 2 | 3 | import "testing" 4 | 5 | func TestIsPalindrome(t *testing.T) { 6 | tests := []struct { 7 | input string 8 | want bool 9 | }{ 10 | {"", true}, 11 | {"a", true}, 12 | {"aa", true}, 13 | {"ab", false}, 14 | {"mom", true}, 15 | {"kayak", true}, 16 | {"dog", false}, 17 | {"été", true}, 18 | {"amanaplanacanalpanama", true}, 19 | {"", true}, 20 | {"", true}, 21 | } 22 | 23 | for _, test := range tests { 24 | if got := IsPalindrome(test.input); got != test.want { 25 | t.Errorf(`IsPalindrone(%q) = %v`, test.input, got) 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/02-donovan-kernighan/readme.md: -------------------------------------------------------------------------------- 1 | All of the code in this folder comes from Donovan & Kernighan's book on Go, or is inpsired by their book. -------------------------------------------------------------------------------- /code_samples_es/011-code-samples/readme.md: -------------------------------------------------------------------------------- 1 | This code is not covered in a video lecture. 2 | 3 | The code in this folder provides examples of code I like. 4 | 5 | This code has been provided so that you can look at it and learn from it. 6 | 7 | To learn more about Go programming, come join my "Go Web Dev" course! 8 | 9 | :) 10 | -------------------------------------------------------------------------------- /code_samples_it/temp.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eduartua/go-programming/bdd92657b387537b69c29f56ec39adf1f259b93e/code_samples_it/temp.txt -------------------------------------------------------------------------------- /section_02/2.01.md: -------------------------------------------------------------------------------- 1 | # Secion 2.1 Playground 2 | 3 | Start with the [Go Playground](https://play.golang.org/). Later, we'll talk about editors and editor tools. 4 | 5 | You can write Go code here. 6 | 7 | ```go 8 | package main 9 | 10 | import ( 11 | "fmt" 12 | ) 13 | 14 | func main() { 15 | fmt.Println("Hello, playground") 16 | } 17 | ``` 18 | We will learn about package, import, func later. For now, let's look at the playground. 19 | 20 | You can click on the share button to share code snippets, if you have questions and want to share some code, you can use this sharing URL. Someone else can troubleshoot it, get a different URL and share that back to you. 21 | 22 | Some useful places to ask questions are: https://forum.golangbridge.org/. A lot of "heavy hitters" in the Go community hang out here. 23 | 24 | In Go, we organize our code into packages. Go has a standard library, organized in packages. Here we're using package `"fmt"` and the `fmt.Prinln` function from that package. From package "fmt" I'm calling the `Println` identifier. 25 | 26 | That's a convention in Go, you have a package, some identifier; a variable, a constant, a function, that has been exported from that package. If you want to automatically import packages from the standard library, just check the Imports button, and when you click the format button, it will import automatically. It will also format you code in an idomatic way. 27 | 28 | When you hear someone say "idiomatic Go code," that is code written in the way that we in the Go community write Go. 29 | 30 | Finally, click Run, and that will run your code. It compiles down to an executable, and execute it. Go compiles down to binary, a straight executable, doesn't run on top of another runtime or virtual machine. It's binary code on the hardware. 31 | 32 | There's a mechanical sympathy that Go achieves. That's sympathy with the machine. Meaning Go will compile for the specific hardware it is running on, and compile in a way that it will run on that hardware in the most efficient way possible. 33 | 34 | -------------------------------------------------------------------------------- /section_02/2.04.md: -------------------------------------------------------------------------------- 1 | # 2.4 The Var Keyword 2 | 3 | We saw the short declaration operator and how it can be used within code blocks. What about when we have a variable we want accessed in a wider scope? 4 | 5 | ```go 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | ) 11 | 12 | func main() { 13 | x := 42 + 7 /* the scope of x is from here down */ 14 | y := "James Bond" /* the scope of y is from here down */ 15 | fmt.Println(x) 16 | fmt.Println(y) 17 | x = 50 18 | fmt.Println(x) 19 | } 20 | ``` 21 | I won't be able to access a variable before it is declared. Nor outside of its scope. 22 | 23 | ```go 24 | package main 25 | 26 | import ( 27 | "fmt" 28 | ) 29 | 30 | func main() { 31 | x := 42 + 7 32 | y := "James Bond" 33 | fmt.Println(x) 34 | fmt.Println(y) 35 | x = 50 36 | fmt.Println(x) 37 | } 38 | 39 | func foo() { 40 | fmt.Println(x) /* x is out of scope here */ 41 | } 42 | 43 | ``` 44 | We get the error `tmp/sandbox324213631/main.go:17: undefined: x`. Line 17 is trying to acess `x`, and it cannot. 45 | 46 | Sometimes, we are going to want a variable scope larger than the code block. If I want scope that is at the package level, I can use `var`. We can ensure our language is correct for the [keywords](https://golang.org/ref/spec#Keywords) by checking out keywords in the Go documentation. 47 | 48 | The var keyword allows us to create a variable. Let's add the variable `z` and set its value to `21`. 49 | 50 | ```go 51 | package main 52 | 53 | import ( 54 | "fmt" 55 | ) 56 | 57 | var z = 21 58 | 59 | func main() { 60 | x := 42 + 7 61 | y := "James Bond" 62 | fmt.Println(x) 63 | fmt.Println(y) 64 | x = 50 65 | fmt.Println(x) 66 | fmt.Println(z) /* z is in scope here as well */ 67 | } 68 | 69 | func foo() { 70 | fmt.Println(z) /* z is in scope anywhere throughout the package */ 71 | } 72 | ``` 73 | 74 | Here's a good coding practice tip: Always use the short declaration operator inside code block to declare and assign a value to a variable. And if you need package level scope, use `var`. 75 | 76 | Some terminology: curly braces `{}`, parentheses `()` 77 | 78 | Recapitulate: To create a variable with a package level scope, we use `var`, the variable name, the equals operator `=`, and the value we wish to assign it, e.g. `var greeting = "Hello there"` 79 | 80 | -------------------------------------------------------------------------------- /section_02/2.06.md: -------------------------------------------------------------------------------- 1 | # 2.6 Zero Value 2 | 3 | To understand the zero value, we also have to understand initialization. In order to do that, let's do a little review about declaring and assigning. 4 | 5 | ```go 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | ) 11 | 12 | var z int // DELCARE a VARIABLE is of TYPE int 13 | 14 | func main() { 15 | z = 21 // ASSIGN a VALUE to that variable 16 | fmt.Println(z) 17 | } 18 | ``` 19 | We _declare_ a variable and its type, then we _assign_ a _value_ of the right type to that variable. 20 | 21 | Initialization is the _initial time you assign a value to a variable_. So, where we have ASSIGN, we could also call that initialize. 22 | 23 | [Initialization](https://en.wikipedia.org/wiki/Initialization_(programming)): In computer programming, initialization is the assignment of an initial value for a data object or variable. 24 | 25 | It's the first time that you assign a value to a variable. Things in a computer are stored in memory. In the computer you have memory. Memory is like a big post office with post office boxes. Each of those PO boxes has an address, and you can store things in each PO box. 26 | 27 | The _initial_ time you store a value in memory, is called initialization. 28 | 29 | So, what happens if we declare a variable but do not assign a value to it, then try to print it out. 30 | 31 | ```go 32 | package main 33 | 34 | import ( 35 | "fmt" 36 | ) 37 | 38 | var z int // DELCARE a VARIABLE is of TYPE int 39 | 40 | func main() { 41 | fmt.Println(z) 42 | } 43 | ``` 44 | `0` 45 | 46 | Every type in Go has a zero value. If you declare a variable to be of a certain type, but we haven't assigned an initial value, then the compiler is going to assign that value for us. For an `int` it is `0`, for float it's `0.0` for a string it's the empty string, for bool it's `false`, and nil for pointers, functions, interfaces, slices, channels, maps. 47 | 48 | The official [documentation for zero value](https://golang.org/ref/spec#The_zero_value) says, "When storage is allocated for a variable, either through a declaration or a call of new, or when a new value is created, either through a composite literal or a call of make, and no explicit initialization is provided, the variable or value is given a default value." 49 | 50 | When storage (or memory) is allocated, and _no explicit initialization is provided_... so when you declare a variable, but don't assign a value, it will be assigned a zero value. 51 | 52 | -------------------------------------------------------------------------------- /section_02/2.08.md: -------------------------------------------------------------------------------- 1 | # 2.8 Creating Your Own Type 2 | 3 | Some people say, "Go is all about 'type.'" Go is a static programming language, and at the heart of a static programming language is that once you declare that a variable is of a certain type, that's static; it doesn't change. 4 | 5 | In the next video, we'll learn about conversion versus casting. 6 | 7 | Let's try creating our own type in the [Go playground](https://play.golang.org/p/9Gv-WWADVj). 8 | 9 | ```go 10 | package main 11 | 12 | import ( 13 | "fmt" 14 | ) 15 | 16 | var a int 17 | type hotdog int 18 | var b hotdog 19 | 20 | func main() { 21 | a = 42 22 | b = 43 23 | fmt.Println(a) 24 | fmt.Printf("%T\n", a) 25 | fmt.Println(b) 26 | fmt.Printf("%T\n", b) 27 | } 28 | ``` 29 | This returns: 30 | ``` 31 | 42 32 | int 33 | 43 34 | main.hotdog 35 | ``` 36 | So we can see that the value of `a` is `42` and it is of type `int`, and the value of `b` is 43 and it is of type `hotdog` from the package `main`. 37 | 38 | We created a type `hotdog` with the line `type hotdog int`, we _declared_ a variable of type `hotdog` with `var b hotdog`, we _assigned a value_ to the variable with `b = 43` 39 | 40 | Go is a static programming language, so if I want to now do something like assign the value of `b` to `a`, with `a = b` the compiler will complain. We cannot take the value of something of type `hotdog` and assign it to something that is of type `int`. 41 | 42 | ```go 43 | package main 44 | 45 | import ( 46 | "fmt" 47 | ) 48 | 49 | var a int 50 | type hotdog int 51 | var b hotdog 52 | 53 | func main() { 54 | a = 42 55 | b = a // we cannot assign the value of a type int to a type hotdog 56 | fmt.Println(a) 57 | fmt.Printf("%T\n", a) 58 | fmt.Println(b) 59 | fmt.Printf("%T\n", b) 60 | } 61 | ``` 62 | returns 63 | `tmp/sandbox982815840/main.go:13: cannot use a (type int) as type hotdog in assignment` 64 | 65 | -------------------------------------------------------------------------------- /section_02/2.09.md: -------------------------------------------------------------------------------- 1 | # 2.9 Conversion, Not Casting 2 | 3 | Conversion means we take the value of one type and _convert_ it to another type. 4 | 5 | Let's try it out in the [Go playground](https://play.golang.org/p/zMIh3Eur7K) 6 | ```go 7 | package main 8 | 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | var a int 14 | type hotdog int 15 | var b hotdog 16 | 17 | func main() { 18 | a = 42 19 | b = hotdog(a) // we can convert the value of a to a value of type hotdog 20 | fmt.Println(a) 21 | fmt.Printf("%T\n", a) 22 | fmt.Println(b) 23 | fmt.Printf("%T\n", b) 24 | } 25 | ``` 26 | In other programming languages, this is called _casting_. We don't call it casting in Go, we call it _conversion_. If you go to [Effective Go](https://golang.org/doc/effective_go.html) and search for "cast" you won't find any results, but if you search for "[conversion](https://golang.org/doc/effective_go.html#conversions)" you will. 27 | 28 | That's the end of this section! We will have some hands on exercises in the next section. 29 | 30 | -------------------------------------------------------------------------------- /section_02_it/temp.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eduartua/go-programming/bdd92657b387537b69c29f56ec39adf1f259b93e/section_02_it/temp.txt -------------------------------------------------------------------------------- /section_02_ja/2.1.md: -------------------------------------------------------------------------------- 1 | # セクション 2: 変数、値、型 2 | 3 | ## 2.1 Playground 4 | 5 | [Go Playground](https://play.golang.org/)から始めましょう。その後で、エディタやツールについて見ていきます。 6 | 7 | 以下のコードをPlaygroundに書いてください。 8 | 9 | ```go 10 | package main 11 | 12 | import ( 13 | "fmt" 14 | ) 15 | 16 | func main() { 17 | fmt.Println("Hello, playground") 18 | } 19 | ``` 20 | 21 | `package`、`import`、`func`については後にして、Playgroundに注目しましょう。 22 | 23 | コードについて疑問があるときはShareボタンをクリックして現れるURLを使ってコードを共有できます。誰かが解決して、別の共有用URLを送ってくれるかもしれません。 24 | 25 | https://forum.golangbridge.org/はGoの質問をするのに良いところです。たくさんのGoの達人たちが待っていますよ。 26 | 27 | Goではコードをパッケージで管理します。Goは基本的なライブラリを備えており、パッケージで管理されています。上記コードでは`"fmt"`パッケージの`fmt.Prinln`関数を使っています。`"fmt"`パッケージから`Println`という識別子を呼び出しているのです。 28 | 29 | Goのルールでは識別子を持つもの、変数、定数、関数はパッケージからエクスポートされます。もし基本ライブラリから自動的にパッケージをインポートしたいなら、`Imports`ボタンをチェックすれば、`Format`ボタンをクリックしたときに自動的にインポートされるようになります。また、`Format`ボタンをクリックするとGoらしいコードにフォーマットされます。 30 | 31 | "Goらしいコード" というのは、GoコミュニティがGoを書くスタイルで書かれたコードのことです。 32 | 33 | ようやく`Run`ボタンをクリックしてコードを実行するときです。実行可能ファイルへとコンパイルし、実行します。Goコンパイラは直接実行可能なバイナリを生成します。他のランタイムや仮想マシンは必要ありません。 34 | 35 | これこそがGoが実現する機械的協調です。これはGoが特定のハードウェアで実行可能で、最も性能を発揮するようにコンパイルすることができるということです。 -------------------------------------------------------------------------------- /section_02_ja/2.3.md: -------------------------------------------------------------------------------- 1 | ## 2.3 短縮形宣言演算子 2 | 3 | 少しだけプログラミング用語の話です。短縮形宣言演算子 `:=` は変数に値を割り当てます。この例では`x`に`42`を割り当てます。(このコードはコンパイルできません。) 4 | 5 | ```go 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | ) 11 | 12 | func main() { 13 | x := 42 14 | fmt.Println("Hello, playground") 15 | } 16 | ``` 17 | 18 | 短縮形宣言はコードブロックの中だけでしかできません。Goでは作成した変数は使わなくはいけません。なので上記のコードは`tmp/sandbox141801923/main.go:8: x declared and not used`のようなエラーになります。 19 | 20 | xを出力すると、エラーにはなりません。Stringのように他の型でも短縮形宣言演算子で割り当てることができます。 21 | 22 | ```go 23 | package main 24 | 25 | import ( 26 | "fmt" 27 | ) 28 | 29 | func main() { 30 | x := 42 31 | y := "James Bond" 32 | fmt.Println(x, y) 33 | } 34 | ``` 35 | 36 | 演算子と被演算子、文と式、そしてキーワードについて説明します。 37 | 38 | プログラミング言語にはキーワード(予約語)があります。プログラミング言語が使う単語で、変数名に使うことはできません。例えば、Goでは"package"は予約されています。 39 | 40 | "package"を変数名として使おうとするとこのようなエラーが起こります。`tmp/sandbox916074896/main.go:8: syntax error: unexpected package, expecting }`(このコードはコンパイルできません。) 41 | 42 | ```go 43 | package main 44 | 45 | import ( 46 | "fmt" 47 | ) 48 | 49 | func main() { 50 | package := 42 51 | y := "James Bond" 52 | fmt.Println(package, y) 53 | } 54 | ``` 55 | 56 | しかし、"packages"のような変化形なら使うことができます。"package"という単語だけがキーワードとして予約されています。 57 | 58 | ```go 59 | package main 60 | 61 | import ( 62 | "fmt" 63 | ) 64 | 65 | func main() { 66 | packages := 42 67 | y := "James Bond" 68 | fmt.Println(packages, y) 69 | } 70 | ``` 71 | 72 | Goの[キーワード](https://golang.org/ref/spec#Keywords) 73 | 74 | ```go 75 | break default func interface select 76 | case defer go map struct 77 | chan else goto package switch 78 | const fallthrough if range type 79 | continue for import return var 80 | ``` 81 | 82 | [演算子とデリミタ](https://golang.org/ref/spec#Operators_and_Delimiters) 83 | 84 | ```go 85 | + & += &= && == != ( ) 86 | - | -= |= || < <= [ ] 87 | * ^ *= ^= <- > >= { } 88 | / << /= <<= ++ = := , ; 89 | % >> %= >>= -- ! ... . : 90 | &^ &^= 91 | ``` 92 | 93 | `:=`を見つけられたと思います。`x := 42 + 7`という文のうち、`+`も演算子です。(加算演算子)`42`と`7`が被演算子です。 94 | 95 | [文](https://ja.wikipedia.org/wiki/%E6%96%87_(%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0))と[式](https://ja.wikipedia.org/wiki/%E5%BC%8F_(%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0))について説明します。`42 + 7`は式です。式は何かを評価して返します。文は通常、式を含み、行のほとんどを占めます。`x := 42 + 7`は文です。 96 | 97 | 「文は最小の単独構成要素であり、式が何らかの結果をもたらします。」 98 | 99 | 「式はプログラミング言語が解釈する一つ以上の値、定数、変数、演算子、関数の組み合わせのことです。それら計算し、別の値を生成します。」 100 | 101 | このセクションで主に伝えたいのは、短縮形宣言演算子`:=`は変数に値を割り当てる主な方法だということです。これはコードブロックの中({}の中)でのみ使うことができます。 102 | 103 | これは動作しません。 104 | 105 | ```go 106 | package main 107 | 108 | import ( 109 | "fmt" 110 | ) 111 | 112 | x := 42 113 | 114 | func main() { 115 | y := "James Bond" 116 | fmt.Println(x, y) 117 | } 118 | ``` 119 | 120 | 関数の中にのみスコープがあり、その後に宣言です。なので以下のコードでは`x`と`y`が宣言されていないことになりエラーが発生します。 121 | 122 | ```go 123 | package main 124 | 125 | import ( 126 | "fmt" 127 | ) 128 | 129 | func main() { 130 | fmt.Println(x, y) /* xとyは宣言されていない */ 131 | x := 42 132 | y := "James Bond" 133 | fmt.Println(x, y) 134 | } 135 | ``` 136 | 137 | 以下のコードでは`tmp/sandbox208846163/main.go:12: no new variables on left side of :=`のようなエラーが発生します。 138 | 139 | ```go 140 | package main 141 | 142 | import ( 143 | "fmt" 144 | ) 145 | 146 | func main() { 147 | x := 42 + 7 148 | y := "James Bond" 149 | fmt.Println(x) 150 | fmt.Println(y) 151 | x := 50 152 | fmt.Println(x) 153 | } 154 | ``` 155 | 156 | このエラーは、`x`が既に存在するという意味です。12行目を`x = 50`に変えれば動作します。 157 | 158 | さて、短縮形宣言演算子がどういうものか見てきました。新しい変数に値を割り当てるものですね。値は`=`演算子を使って変更することができます。プログラミング用語である文と式についても学びました。 159 | 160 | 次のビデオでは、コードブロックの外で変数を宣言し値を割り当てる別の方法を見ていきます。 -------------------------------------------------------------------------------- /section_02_ja/2.4.md: -------------------------------------------------------------------------------- 1 | ## 2.4 varキーワード 2 | 3 | 短縮形宣言演算子についてコードブロック内でどのように使うか見てきました。では、より広いスコープでアクセスしたい変数がある場合はどうすればよいのでしょう? 4 | 5 | ```go 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | ) 11 | 12 | func main() { 13 | x := 42 + 7 /* xのスコープはここから以下 */ 14 | y := "James Bond" /* yのスコープはここから以下 */ 15 | fmt.Println(x) 16 | fmt.Println(y) 17 | x = 50 18 | fmt.Println(x) 19 | } 20 | ``` 21 | 22 | 変数の宣言前にアクセスすることはできません。スコープの外だからです。(以下のコードはコンパイルできません。) 23 | 24 | ```go 25 | package main 26 | 27 | import ( 28 | "fmt" 29 | ) 30 | 31 | func main() { 32 | x := 42 + 7 33 | y := "James Bond" 34 | fmt.Println(x) 35 | fmt.Println(y) 36 | x = 50 37 | fmt.Println(x) 38 | } 39 | 40 | func foo() { 41 | fmt.Println(x) /* xはスコープから外れている */ 42 | } 43 | ``` 44 | 45 | `tmp/sandbox324213631/main.go:17: undefined: x`といったエラーが出るでしょう。17行目で`x`にアクセスしようとしていますが、できないからです。 46 | 47 | ときにはコードブロックのスコープよりも広い範囲の変数スコープが欲しいこともあるでしょう。`var`を使えばパッケージレベルのスコープを得られます。Goドキュメントの[keywords](https://golang.org/ref/spec#Keywords)を見てキーワードを確認してみましょう。 48 | 49 | `var`キーワードは変数の作成のために使います。変数`z`を追加し、21を割り当てます。 50 | 51 | ```go 52 | package main 53 | 54 | import ( 55 | "fmt" 56 | ) 57 | 58 | var z = 21 59 | 60 | func main() { 61 | x := 42 + 7 62 | y := "James Bond" 63 | fmt.Println(x) 64 | fmt.Println(y) 65 | x = 50 66 | fmt.Println(x) 67 | fmt.Println(z) /* zはここでもスコープ内 */ 68 | } 69 | 70 | func foo() { 71 | fmt.Println(z) /* zはパッケージ内ならどこでもスコープ内 */ 72 | } 73 | ``` 74 | 75 | 良いコードのために: 変数宣言と値の割り当てのために、コードブロック内では常に短縮形宣言演算子を使うようにしましょう。もしパッケージレベルでのスコープが必要なときだけ`var`を使うと良いでしょう。 76 | 77 | まとめ: パッケージレベルで変数を作成したい場合は`var`を使います。このように使います。`var greeting = "Hello there"` -------------------------------------------------------------------------------- /section_02_ja/2.5.md: -------------------------------------------------------------------------------- 1 | ## 2.5 型探求 2 | 3 | Goは静的型付け言語です。変数を宣言し、値を持つには型が必要です。特定の値を持つ変数を宣言したら、その変数は同じ型だけのみ持つことになります。__変数__を特定の__型__で__宣言__したら同じ__型__しか持てません。 4 | 5 | ここまで変数宣言はこのようにしてきましたね。 6 | 7 | ```go 8 | package main 9 | 10 | import ( 11 | "fmt" 12 | ) 13 | 14 | var z = 21 15 | 16 | func main() { 17 | x := 42 + 7 18 | y := "James Bond" 19 | fmt.Println(x) 20 | fmt.Println(y) 21 | x = 50 22 | fmt.Println(x) 23 | fmt.Println(z) /* zはここでもスコープ内 */ 24 | } 25 | 26 | func foo() { 27 | fmt.Println(z) /* zはパッケージ内ならどこでもスコープ内 */ 28 | } 29 | ``` 30 | 31 | 短縮形宣言演算子または`var`キーワードを使った変数の宣言で、コンパイラは割り当てた値の型を理解します。 32 | 33 | Goの設計者は容易なプログラミングを重要なもののひとつとして考えました。効率的な実行(パフォーマンス)、効率的なコンパイル(永遠かのようなビルド時間を待たなくて済むように)、そして容易なプログラミングです。最高ですね。 34 | 35 | もう少し詳しくいうと、`var z = 21`は`var z int = 21`と同じだということです。 36 | 37 | ```go 38 | package main 39 | 40 | import ( 41 | "fmt" 42 | ) 43 | 44 | var z int = 21 45 | 46 | func main() { 47 | fmt.Println(z) 48 | } 49 | ``` 50 | 51 | 型についてのさまざまなことは後のセクションで見ていきます。 52 | 53 | 型込みで`var z`を宣言した後、値を割り当てることもできます。 54 | 55 | ```GO 56 | package main 57 | 58 | import ( 59 | "fmt" 60 | ) 61 | 62 | var z int 63 | 64 | func main() { 65 | z = 21 66 | fmt.Println(z) 67 | } 68 | ``` 69 | 70 | 変数`z`を`int`として宣言しそこで値を割り当てず、コードブロックの外で割り当てることはできません。(このコードはコンパイルできません。) 71 | 72 | ```go 73 | package main 74 | 75 | import ( 76 | "fmt" 77 | ) 78 | 79 | var z int 80 | z = 21 81 | 82 | func main() { 83 | fmt.Println(z) 84 | } 85 | ``` 86 | 87 | `tmp/sandbox147413757/main.go:8: syntax error: non-declaration statement outside function body` 88 | 89 | 宣言文は関数の外側にのみ置くことができます。 90 | 91 | ここで、[プリミティブ型](https://ja.wikipedia.org/wiki/%E3%83%97%E3%83%AA%E3%83%9F%E3%83%86%E3%82%A3%E3%83%96%E5%9E%8B)と[複合データ型](https://en.wikipedia.org/wiki/Composite_data_type)については知っておくと良いでしょう。 92 | 93 | プリミティブ型はプログラミング用語によって組み込みで提供される基本的なブロックもしくはデータ型のことです。`int`、`string`、`bool`のような基本的かつ組み込みの型という理解で大丈夫です。また、複合データ型にも使われます。つまり、基本的にプリミティブ型は言語によって提供され複合データ型でもあるか、言語によって提供されるが複合データ型でなかったりします。 94 | 95 | 複合データ型はある型の値を組み合わせる、もしくは集めたものです。プログラミング言語によって提供されたりされなかったりします。複合データ型は`int`、`string`、`bool`のような基本的なデータ型をひとまとめにするデータ構造を持ちます。 96 | 97 | プリミティブ型は`slice`、 `array`、 `structure`、 `struct`に。また、複合データ型はまとめられている他の値のデータ型も保持します。 98 | 99 | まとめです。ある型で宣言した変数にはその型の値のみを持つことができます。このように宣言と同時に型を指定することもできます。`var z int = 21`また、宣言後に値を割り当てる場合は、関数の中でのみすることができます。 100 | 101 | ```go 102 | package main 103 | 104 | import ( 105 | "fmt" 106 | ) 107 | 108 | var z int 109 | 110 | func main() { 111 | z = 21 112 | fmt.Println(z) 113 | } 114 | ``` 115 | 116 | プリミティブ型と複合データ型についても学びました。プリミティブ型は`string`、`bool`、`int`のようなプログラミング言語によって提供されるデータ型であり、複合データ型を構成します。複合データ型は異なる型の複数の値等を束ねるデータ構造を持つことができます。 -------------------------------------------------------------------------------- /section_02_ja/2.6.md: -------------------------------------------------------------------------------- 1 | ## 2.6 ゼロ値 2 | 3 | ゼロ値を理解するニアh、初期化を理解しなくてはいけません。そのために、宣言と割り当てについて復習しましょう。 4 | 5 | ```go 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | ) 11 | 12 | var z int // 型intの変数を宣言 13 | 14 | func main() { 15 | z = 21 // 変数に型を割り当て 16 | fmt.Println(z) 17 | } 18 | ``` 19 | 型とともに変数を__宣言__し、ふさわしい__型__の値を__割り当て__ています。 20 | 21 | 初期化とは_変数に値を割り当てる最初のときのこと_です。つまり、割り当てのことを初期化とも呼べるでしょう。 22 | 23 | [初期化](https://en.wikipedia.org/wiki/Initialization_(programming)): プログラミングにおいて、初期化とはデータオブジェクトや変数に最初の値を割り当てることを言う。 24 | 25 | 変数に値を割り当てる最初のときです。コンピュータのあれそれはメモリに保存されています。コンピュータにはメモリがあり、メモリとは大きな郵便箱を備えた郵便局のようなものです。私書箱にはそれぞれ住所があり、それぞれにあれそれを保存できます。 26 | 27 | メモリに値を保存する時のことを初期化といいます。 28 | 29 | 変数を宣言して値を割り当てないときに値を出力してみましょう。 30 | 31 | ```go 32 | package main 33 | 34 | import ( 35 | "fmt" 36 | ) 37 | 38 | var z int // 型intの変数を宣言 39 | 40 | func main() { 41 | fmt.Println(z) 42 | } 43 | ``` 44 | `0` 45 | 46 | Goのどの型にもゼロ値があります。ある型で変数を宣言して初期値を割り当てないとき、コンパイラはゼロ値を割り当てます。`int`のときは`0`、`float`のときは`0.0`、`string`のときは空文字、`bool`のときは`false`、ポインタ、関数、インターフェイス、スライス、チャネル、マップのときは`nil`です。 47 | 48 | 公式の[documentation for zero value](https://golang.org/ref/spec#The_zero_value)では、「変数のためのストレージが確保されたとき、宣言されたときでも`new`が呼び出されたときも、もしくは複合リテラルか`make`が呼び出されたときも、明白な初期化がなければ変数にはデフォルト値が割り当てられます」とあります。 49 | 50 | ストレージ(メモリ)が確保された時、そして__明白な初期化がないとき__…つまり、変数を宣言しても値を割り当てないときはゼロ値が割り当てられます。 51 | 52 | -------------------------------------------------------------------------------- /section_02_ja/2.8.md: -------------------------------------------------------------------------------- 1 | ## 2.8 自分の型を作る 2 | 3 | 人は「Goは`型`が全てだ」と言います。Goは静的プログラミング言語であり、一度変数をある型で宣言したなら変更することはできません。静的なので。 4 | 5 | 次のビデオで型の変換とキャストについて見ていきます。 6 | 7 | 自分の型を作ってみましょう。[Go playground](https://play.golang.org/p/9Gv-WWADVj) 8 | 9 | ```go 10 | package main 11 | 12 | import ( 13 | "fmt" 14 | ) 15 | 16 | var a int 17 | 18 | type hotdog int 19 | 20 | var b hotdog 21 | 22 | func main() { 23 | a = 42 24 | b = 43 25 | fmt.Println(a) 26 | fmt.Printf("%T\n", a) 27 | fmt.Println(b) 28 | fmt.Printf("%T\n", b) 29 | } 30 | ``` 31 | 32 | これはこのような値を返します。 33 | 34 | ``` 35 | 42 36 | int 37 | 43 38 | main.hotdog 39 | ``` 40 | 41 | `a`の値は`42`であり、型は`int`です。`b`の値は`43`であり、型は`main`パッケージ内の`hotdog`になっています。 42 | 43 | `type hotdog int`によって型を作り、`hotdog`型の変数を`var b hotdog`で宣言しました。変数に値を割り当てるのは`b = 43`で行いました。 44 | 45 | Goは静的プログラミング言語なので、`a = b`のようにして、`b`の値を`a`に割り当てようとしても、コンパイラが許しません。`hotdog`型のものを`int`型には割り当てられないのです。(このコードはコンパイルできません。) 46 | 47 | ```go 48 | package main 49 | 50 | import ( 51 | "fmt" 52 | ) 53 | 54 | var a int 55 | 56 | type hotdog int 57 | 58 | var b hotdog 59 | 60 | func main() { 61 | a = 42 62 | b = a // `int`型の値を`hotdog`型の変数には割り当てられない 63 | fmt.Println(a) 64 | fmt.Printf("%T\n", a) 65 | fmt.Println(b) 66 | fmt.Printf("%T\n", b) 67 | } 68 | ``` 69 | 70 | `tmp/sandbox982815840/main.go:13: cannot use a (type int) as type hotdog in assignment`のようなエラーが起こります。 71 | 72 | -------------------------------------------------------------------------------- /section_02_ja/2.9.md: -------------------------------------------------------------------------------- 1 | ## 2.9 型変換(キャストじゃないよ) 2 | 3 | 型変換は他の型へある値の型を変換することです。 4 | 5 | [Go playground](https://play.golang.org/p/zMIh3Eur7K)で試してみましょう。 6 | 7 | ```go 8 | package main 9 | 10 | import ( 11 | "fmt" 12 | ) 13 | 14 | var a int 15 | 16 | type hotdog int 17 | 18 | var b hotdog 19 | 20 | func main() { 21 | a = 42 22 | b = hotdog(a) // hotdog型の値に変換しています 23 | fmt.Println(a) 24 | fmt.Printf("%T\n", a) 25 | fmt.Println(b) 26 | fmt.Printf("%T\n", b) 27 | } 28 | ``` 29 | 30 | 他のプログラミング言語では、これはキャストと呼ばれています。Goではキャストではなく、型変換といいます。[Effective Go](https://golang.org/doc/effective_go.html)で"cast"を検索しても何もヒットしないでしょう。けど[conversion](https://golang.org/doc/effective_go.html#conversions)ならヒットするはずです。 31 | 32 | これでこのセクションは終わりです!次のセクションでは練習問題をやっていきましょう。 33 | -------------------------------------------------------------------------------- /section_03/3.01.md: -------------------------------------------------------------------------------- 1 | # Hands-on Exercise #1 2 | 3 | 1. Using the short declaration operator, ASSIGN these VALUES to VARIABLES with the IDENTIFIERS `x` and `y` and `z` 4 | a. `42` 5 | b. `James Bond` 6 | c. `true` 7 | 8 | 2. Now print the values stored in those variables using 9 | a. A single print statement 10 | b. Multiple print statements 11 | 12 | [answer](https://play.golang.org/p/d7HWHh9n9U) 13 | -------------------------------------------------------------------------------- /section_03/3.02.md: -------------------------------------------------------------------------------- 1 | # Hands-on Exercise #2 2 | 3 | 1. Use var to DECLARE three variables. The variables should have package level scope. Do not assign VALUES to the variables. Use the following IDENTIFIERS for the variables and make sure the variables are of the follow TYPE: 4 | a. identifier `x` type int 5 | b. identifier `y` type int 6 | c. identifier `z` type int 7 | 8 | 2. in `func main` 9 | a. print out the values for each identifier 10 | b. the compiler assigned values to the variables. What are these values called? 11 | 12 | [answer](https://play.golang.org/p/N3xbuFcxMy) 13 | 14 | -------------------------------------------------------------------------------- /section_03/3.03.md: -------------------------------------------------------------------------------- 1 | # Hands-on Exercise #3 2 | 3 | Using the code from the [previous exercise](https://play.golang.org/p/N3xbuFcxMy), 4 | 5 | 1. at the package level scope, assign the following values to the three variables 6 | a. for `x` assign `42` 7 | b. for `y` assign `"James Bond"` 8 | c. for `z` assign `true` 9 | 10 | 2. in `func main` 11 | a. use `fmt.Sprintf` to print all of the VALUES to one single string. ASSIGN the returned value of type string using the short declaration operator to a VARIABLE with the IDENTIFIER `s` 12 | 13 | [answer](https://play.golang.org/p/1HUBT9-WDo) 14 | 15 | -------------------------------------------------------------------------------- /section_03/3.04.md: -------------------------------------------------------------------------------- 1 | # Hands-on Exercise #4 2 | 3 | FYI: Documentation and new terminology "[underlying type](https://golang.org/ref/spec#Types)" 4 | 5 | For this exercise 6 | 7 | 1. create your own type. Have the underlying type be an `int`. 8 | 2. create a VARIABLE of your new TYPE with the IDENTIFIER `x` using the `var` keyword 9 | 3. in `func main` 10 | a. print out the value of the variable `x` 11 | b. print out the type of the variable `x` 12 | c. assign `42` to the variable `x` using the `=` OPERATOR 13 | d. print out the value of the variable `x` 14 | 15 | [answer](https://play.golang.org/p/IXcSrHDVu2) 16 | 17 | -------------------------------------------------------------------------------- /section_03/3.05.md: -------------------------------------------------------------------------------- 1 | # Hands-on Exercise #5 2 | 3 | Building on the code from the [previous example](https://play.golang.org/p/IXcSrHDVu2) 4 | 1. at the package level scope, using the `var` keyword, create a VARIABLE with the IDENTIFIER `y`. The variable should be of the UNDERLYING TYPE of your custom type `x`. 5 | 2. in `func main` 6 | a. this should already be done 7 | - print out the value of the variable `x` 8 | - print out the type of the variable `x` 9 | - assign your own VALUE to the VARIABLE `x` using the `=` OPERATOR 10 | - print out the value of the variable `x` 11 | b. now do this 12 | - now use CONVERSION to convert the TYPE of the VALUE stored in `x` to the UNDERLYING TYPE 13 | 1. then use the short declaration operator to ASSIGN that value to `y` 14 | 15 | [answer](https://play.golang.org/p/cRMA1HvSeg) 16 | 17 | -------------------------------------------------------------------------------- /section_03_ja/3.1.md: -------------------------------------------------------------------------------- 1 | # 練習問題 #1 2 | 3 | 1. 短縮形宣言演算子を使って、a、b、cのそれぞれの値をx、y、zに割り当ててください。 4 | a. `42` 5 | b. `James Bond` 6 | c. `true` 7 | 8 | 2. 保存された値を出力してください。 9 | a. 1つの文で 10 | b. 複数の文で 11 | 12 | [解答](https://play.golang.org/p/d7HWHh9n9U) 13 | -------------------------------------------------------------------------------- /section_03_ja/3.2.md: -------------------------------------------------------------------------------- 1 | # 練習問題 #2 2 | 3 | 1. `var`を使ってパッケージレベルのスコープの変数を3つ宣言してください。値を割り当ててはいけません。3つの変数の条件は以下のとおりです。 4 | a. 識別子 `x` 型 int 5 | b. 識別子 `y` 型 string 6 | c. 識別子 `z` 型 bool 7 | 8 | 2. `main`関数内で 9 | a. それぞれの変数の値を出力してください。 10 | b. コンパイラが変数に値を割り当てたはずです。それらの値のことを何と言いますか? 11 | 12 | [解答](https://play.golang.org/p/MyZ_PFW_kq) 13 | 14 | -------------------------------------------------------------------------------- /section_03_ja/3.3.md: -------------------------------------------------------------------------------- 1 | # 練習問題 #3 2 | 3 | [1つ前の練習問題のコード](https://play.golang.org/p/MyZ_PFW_kq)を使って、 4 | 5 | 1. パッケージレベルのスコープで次の内容の変数を宣言し値を割り当ててください。 6 | a. `x`に`42` 7 | b. `y`に`"James Bond"` 8 | c. `z`に`true` 9 | 10 | 2. `main`関数で 11 | a. `fmt.Sprintf`を使って、全ての変数を1つの文字列にして出力してください。その返り値を短縮形宣言演算子を使って`s`という識別子で型`string`の変数の値として割り当ててください。`s`を出力してください。 12 | 13 | [解答](https://play.golang.org/p/1HUBT9-WDo) 14 | 15 | -------------------------------------------------------------------------------- /section_03_ja/3.4.md: -------------------------------------------------------------------------------- 1 | # 練習問題 #4 2 | 3 | 補足: この練習問題のためのドキュメントはこちら(英語) "[型](https://golang.org/ref/spec#Types)" 4 | 5 | 1. オリジナルの`int`型を基礎として型を宣言してください。 6 | 2. `var`を使って先ほどの型の変数`x`を宣言してください。 7 | 3. `main`関数で 8 | a. 変数`x`の値を出力してください。 9 | b. 変数`x`の型を出力してください。 10 | c. 変数`x`に`=`演算子を使って`42`を割り当ててください。 11 | d. 変数`x`の値を出力してください。 12 | 13 | [解答](https://play.golang.org/p/IXcSrHDVu2) 14 | 15 | -------------------------------------------------------------------------------- /section_03_ja/3.5.md: -------------------------------------------------------------------------------- 1 | # 練習問題 #5 2 | 3 | [1つ前の練習問題のコード](https://play.golang.org/p/IXcSrHDVu2)を使って、 4 | 5 | 1. パッケージレベルスコープで、`var`を使って識別子`y`を宣言してください。`y`の型は`x`が基礎とした型にしてください。 6 | 2. `main`関数で 7 | a. この問題の内容は1つ前の練習問題で終わっているはずです。 8 | - 変数`x`の値を出力してください。 9 | - 変数`x`の型を出力してください 10 | - 変数`x`に`=`演算子を使って`42`を割り当ててください。 11 | - 変数`x`の値を出力してください。 12 | b. ここからが新しい問題です。 13 | 1. `x`の値を`x`が基礎とした型に変換してください。 14 | 2. その値を`y`に割り当て、`y`の値を出力してください。 15 | 16 | [解答](https://play.golang.org/p/cRMA1HvSeg) 17 | 18 | -------------------------------------------------------------------------------- /section_03_ja/3.6.md: -------------------------------------------------------------------------------- 1 | # 練習問題 #6 2 | 3 | [クイズ](https://docs.google.com/forms/d/e/1FAIpQLSfyN4xMJZPoz_2bVy-BXctXfb1a64n4deYF9jj6JLnhpwA3dw/viewform)をやってみましょう。 4 | 5 | 1. 何かを実行するのに最小のプログラム構成要素は? 6 | 7 | - [ ] 文 8 | - [ ] 式 9 | 10 | 2. 一つもしくは複数の値、定数、変数、演算子、関数の組み合わせで、プログラミング言語が解釈、計算して他の値を導くものは? 11 | 12 | - [ ] 文 13 | - [ ] 式 14 | 15 | 3. 「丸括弧」はどれでしょう? 16 | 17 | - [ ] () 18 | - [ ] {} 19 | - [ ] [] 20 | 21 | 4. 「波括弧」はどれでしょう? 22 | 23 | - [ ] () 24 | - [ ] {} 25 | - [ ] [] 26 | 27 | 5. 「角括弧」はどれでしょう? 28 | 29 | - [ ] () 30 | - [ ] {} 31 | - [ ] [] 32 | 33 | 6. 変数のスコープとは、出力したり値を読み込んだり変数へのアクセスできる場所のことである。 34 | 35 | - [ ] ○ 36 | - [ ] ✗ 37 | 38 | 7. プリミティブ型とは、言語組み込みのものであり、基礎的な型である。 39 | 40 | - [ ] ○ 41 | - [ ] ✗ 42 | 43 | 8. Goでは、`int`はプリミティブ型である。 44 | 45 | - [ ] ○ 46 | - [ ] ✗ 47 | 48 | 9. Goでは、`string`はプリミティブ型である。 49 | 50 | - [ ] ○ 51 | - [ ] ✗ 52 | 53 | 10. 複合データ型は他の型ををまとめることのできる型である。 54 | 55 | - [ ] ○ 56 | - [ ] ✗ 57 | 58 | 11. Goでは`var`を使って変数が宣言され、値が割り当てられてない時、コンパイラがデフォルトの値をを変数に割り当てる。これは「ゼロ値」と呼ばれている。 59 | 60 | - [ ] ○ 61 | - [ ] ✗ 62 | 63 | 12. キーワードとは、Goによって予約されている言葉である。特定の目的のために特定の方法で使われる。 64 | 65 | - [ ] ○ 66 | - [ ] ✗ 67 | 68 | 13. キーワードは「予約語」とも呼ばれる。 69 | 70 | - [ ] ○ 71 | - [ ] ✗ 72 | 73 | 14. キーワードはそのキーワードの目的以外のどのような場合にも使うことはできない。 74 | 75 | - [ ] ○ 76 | - [ ] ✗ 77 | 78 | 15. `2 + 2`の`+`は演算子である。 79 | 80 | - [ ] ○ 81 | - [ ] ✗ 82 | 83 | 16. `2 + 2`の`2`は被演算子である。 84 | 85 | - [ ] ○ 86 | - [ ] ✗ 87 | 88 | 17. [golang.org](https://golang.org/)で見つかるドキュメントと[godoc.org](http://godoc.org/で見つかるドキュメントは何が違う? 89 | 90 | 18. `package`は予約語である。 91 | 92 | - [ ] ○ 93 | - [ ] ✗ 94 | 95 | 19. `var`は予約語である。 96 | 97 | - [ ] ○ 98 | - [ ] ✗ 99 | 100 | 20. プログラムの入り口である`func main()`はmainパッケージに必要である。 101 | 102 | - [ ] ○ 103 | - [ ] ✗ 104 | 105 | 21. 短縮形宣言演算子はプログラムのパッケージレベル、ブロックレベルなどどこでも使うことができる。 106 | 107 | - [ ] ○ 108 | - [ ] ✗ 109 | 110 | 22. "effective go"では良いパッケージ名を表す3つの言葉はなんだとしている? 111 | 112 | - [ ] descriptive(記述的) 113 | - [ ] short(短い) 114 | - [ ] concise(簡潔) 115 | - [ ] evocative(喚起的) 116 | 117 | 23. オンラインでGoのコードを書いたり実行できるウェブサイトの名前と言えば? 118 | 119 | 24. Goの質問をするのに最適な"golang bridge forum"はhttps://forum.golangbridge.org/である。 120 | 121 | - [ ] ○ 122 | - [ ] ✗ 123 | 124 | 25. `fmt.Println()`は`Println()`関数を`fmt`パッケージから呼び出すものである。 125 | 126 | - [ ] ○ 127 | - [ ] ✗ 128 | 129 | 26. 「識別子」とは変数、関数、定数の名前として割り当てられるものである。 130 | 131 | - [ ] ○ 132 | - [ ] ✗ 133 | 134 | 27. 関数、変数、定数をパッケージからを呼び出す時は「パッケージドット記法」を使う。例 `fmt.Println()` 135 | 136 | - [ ] ○ 137 | - [ ] ✗ 138 | 139 | 28. 「Goらしいコード」とは何か? 140 | 141 | 29. 「返り値を捨てる」もしくは「返り値をvoidに送る」ときに使う文字は?言い換えると、関数の返り値を使わないことをコンパイラに伝える文字は? 142 | 143 | - [ ] # 144 | - [ ] @ 145 | - [ ] _ 146 | - [ ] この問題はひっかけ問題だ 147 | 148 | 30. Goでは、使わない変数をそのままに置いておくことはできない。 149 | 150 | - [ ] ○ 151 | - [ ] ✗ 152 | 153 | 31. 関数が`...interface{}`という型のパラメータをもっている時、「可変長引数」とも呼ばれ、いくつでも、どの型の引数でもその関数がとることができることを意味する。 154 | 155 | - [ ] ○ 156 | - [ ] ✗ 157 | 158 | 32. Goにおけるどの値も「空のインターフェイス」でもある。空のインターフェイスはこのようなに表される `interface{}` 159 | 160 | - [ ] ○ 161 | - [ ] ✗ 162 | 163 | 33. 文はコンピューターが何かを実行するための命令である。通常プログラム中の行を構成する。 164 | 165 | - [ ] ○ 166 | - [ ] ✗ 167 | 168 | 34. 式は一つもしくは複数の値、定数、変数、演算子、関数の組み合わせで、プログラミング言語が解釈、計算して他の値を導くものである。例えば、`2 + 3`は式であり、評価して`5`になる。 169 | 170 | - [ ] ○ 171 | - [ ] ✗ 172 | 173 | 35. 文字列を出力して、変数にその文字列を割り当てたい時、`fmt`パッケージの`Sprintf()`関数を使うことができる。 174 | 175 | - [ ] ○ 176 | - [ ] ✗ 177 | 178 | 36. Goでは、自身の型を作ることができる。 179 | 180 | - [ ] ○ 181 | - [ ] ✗ 182 | 183 | 37. Goでは、「キャスト」ではなく「変換」という。 184 | 185 | - [ ] ○ 186 | - [ ] ✗ 187 | 188 | 38. 言語について話すのに言語がある。 189 | 190 | - [ ] ○ 191 | - [ ] ✗ 192 | 193 | 39. Goで自身の型を作る時、その型には「基礎とする型」がある。 194 | 195 | - [ ] ○ 196 | - [ ] ✗ 197 | 198 | 199 | -------------------------------------------------------------------------------- /section_04/4.06.md: -------------------------------------------------------------------------------- 1 | # Section 4.6 Constants 2 | 3 | If you wanted to find out whether `const` was a keyword, how would you do so? 4 | 5 | ```go 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | ) 11 | 12 | const 13 | 14 | func main() { 15 | fmt.Println("Hello, playground") 16 | } 17 | 18 | ``` 19 | 20 | [The Go Programming Language Specification](https://golang.org/ref/spec) is a great place to start. The [Keywords](https://golang.org/ref/spec#Keywords) section holds the answer. 21 | 22 | ``` 23 | break default func interface select 24 | case defer go map struct 25 | chan else goto package switch 26 | const fallthrough if range type 27 | continue for import return var 28 | ``` 29 | 30 | Make a few constants using the [Go playground](https://play.golang.org/p/et5Qf-Crsu). The Go compiler will figure out what type they are for you. 31 | ```go 32 | package main 33 | 34 | import ( 35 | "fmt" 36 | ) 37 | 38 | const a = 42 39 | const b = 42.78 40 | const c = "James Bond" 41 | 42 | func main() { 43 | fmt.Println(a) 44 | fmt.Println(b) 45 | fmt.Println(c) 46 | fmt.Printf("%T\n", a) 47 | fmt.Printf("%T\n", b) 48 | fmt.Printf("%T\n", c) 49 | } 50 | 51 | ``` 52 | 53 | An alternative way to declare several constants and assign values is using similar syntax to our `import` statement. 54 | 55 | ```go 56 | package main 57 | 58 | import ( 59 | "fmt" 60 | ) 61 | 62 | const ( 63 | a = 42 64 | b = 42.78 65 | c = "James Bond" 66 | ) 67 | 68 | func main() { 69 | fmt.Println(a) 70 | fmt.Println(b) 71 | fmt.Println(c) 72 | fmt.Printf("%T\n", a) 73 | fmt.Printf("%T\n", b) 74 | fmt.Printf("%T\n", c) 75 | } 76 | 77 | ``` 78 | [playground](https://play.golang.org/p/N3_-plSitG) 79 | 80 | If we want to specify the type of our constants, we can. Currently, they are untyped and are known as _constants of a kind_. That gives the compiler a bit of flexibility, because with constants of a kind, or constants which are untyped, the compiler decides which types to assign which values to. When it is typed, it doesn't have that flexibility. 81 | 82 | ```go 83 | package main 84 | 85 | import ( 86 | "fmt" 87 | ) 88 | 89 | const ( 90 | a int = 42 91 | b float32 = 42.78 92 | c string = "James Bond" 93 | ) 94 | 95 | func main() { 96 | fmt.Println(a) 97 | fmt.Println(b) 98 | fmt.Println(c) 99 | fmt.Printf("%T\n", a) 100 | fmt.Printf("%T\n", b) 101 | fmt.Printf("%T\n", c) 102 | } 103 | 104 | ``` 105 | [playground](https://play.golang.org/p/zs-UzDM_Q7) 106 | -------------------------------------------------------------------------------- /section_04/4.07.md: -------------------------------------------------------------------------------- 1 | # Section 4.7: Iota 2 | 3 | In the [Go Specification](https://golang.org/ref/spec), near the end of the section on [constant declarations](https://golang.org/ref/spec#Constant_declarations), it assigns the value [iota](https://golang.org/ref/spec#Iota) to a `const`. 4 | 5 | `Iota` is the predeclared identifier. 6 | 7 | ```go 8 | package main 9 | 10 | import ( 11 | "fmt" 12 | ) 13 | 14 | const ( 15 | a = iota 16 | b = iota 17 | c = iota 18 | ) 19 | 20 | func main() { 21 | fmt.Println(a) 22 | fmt.Println(b) 23 | fmt.Println(c) 24 | 25 | fmt.Printf("%T\n", a) 26 | fmt.Printf("%T\n", b) 27 | fmt.Printf("%T\n", c) 28 | } 29 | ``` 30 | 31 | [playground](https://play.golang.org/p/mkQlg_SX4L) 32 | 33 | You can see this gives us the auto incrementing values, 0, 1, 2. A shorthand for declaring auto incremented constant values is to just set the first one to `iota` 34 | 35 | ```go 36 | package main 37 | 38 | import ( 39 | "fmt" 40 | ) 41 | 42 | const ( 43 | a = iota 44 | b 45 | c 46 | ) 47 | 48 | const ( 49 | d = iota 50 | e 51 | f 52 | ) 53 | 54 | func main() { 55 | fmt.Println(a) 56 | fmt.Println(b) 57 | fmt.Println(c) 58 | fmt.Println(d) 59 | fmt.Println(e) 60 | fmt.Println(f) 61 | } 62 | 63 | ``` 64 | 65 | You can see the auto incrementing restarts in each new group of const declarations. 66 | -------------------------------------------------------------------------------- /section_04/4.08.md: -------------------------------------------------------------------------------- 1 | # Section 4.8: Bit Shifting 2 | 3 | In section [4.5: Numeral System](../section_4/4.5.md), we covered the hexadecimal numbering system, which is base 16. We also saw the binary numbering system which is all 0s and 1s. 4 | 5 | So in binary the numbers 1, 2, 3 are represented as 1, 10, 11. There is a concept called [bit shifting](https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts). 6 | 7 | Imagine we have `0000 0010`, we can perform an operation that takes the bit and shifts it to `0000 0100`. 8 | 9 | If we look at [Operators and Punctuation](https://golang.org/ref/spec#Operators_and_punctuation) the `<<` and `>>` operators have to do with shifting bits. 10 | 11 | ```go 12 | package main 13 | 14 | import ( 15 | "fmt" 16 | ) 17 | 18 | 19 | func main() { 20 | x := 4 21 | fmt.Printf("decimal: %d\t\tbinary: %b\n", x, x) 22 | 23 | y := x << 1 24 | fmt.Printf("decimal: %d\t\tbinary: %b\n", y, y) 25 | 26 | z := x >> 1 27 | fmt.Printf("decimal: %d\t\tbinary: %b\n", z, z) 28 | } 29 | 30 | ``` 31 | The result is: 32 | ``` 33 | decimal: 4 binary: 100 34 | decimal: 8 binary: 1000 35 | decimal: 2 binary: 10 36 | ``` 37 | [playground](https://play.golang.org/p/NYOejCbw7Y) 38 | You can see we shifted the bit over 1 space. So bit shifting using `<<` is moving us from `100` to `1000` and bit shifting using `>>` is moving us from `100` to `10`. 39 | 40 | If we look at the change in size from kb to mb to gb, we can see it shifts to the left 10 times. 41 | ```go 42 | package main 43 | 44 | import ( 45 | "fmt" 46 | ) 47 | 48 | 49 | func main() { 50 | kb := 1024 51 | mb := 1024 * kb 52 | gb := 1024 * mb 53 | 54 | fmt.Printf("kb: decimal: %d \t\tbinary: %b\n", kb, kb) 55 | fmt.Printf("mb: decimal: %d \t\tbinary: %b\n", mb, mb) 56 | fmt.Printf("gb: decimal: %d \tbinary: %b\n", gb, gb) 57 | } 58 | ``` 59 | [playground](https://play.golang.org/p/3TA6lwpkfr) 60 | 61 | ``` 62 | kb: decimal: 1024 binary: 10000000000 63 | mb: decimal: 1048576 binary: 100000000000000000000 64 | gb: decimal: 1073741824 binary: 1000000000000000000000000000000 65 | ``` 66 | 67 | We can use [iota](https://golang.org/ref/spec#Iota) with this as well 68 | ```go 69 | package main 70 | 71 | import ( 72 | "fmt" 73 | ) 74 | 75 | const ( 76 | _ = iota 77 | // kb = 1024 78 | kb = 1 << (iota * 10) 79 | mb = 1 << (iota * 10) 80 | gb = 1 << (iota * 10) 81 | ) 82 | 83 | func main() { 84 | fmt.Printf("kb: decimal: %d \t\tbinary: %b\n", kb, kb) 85 | fmt.Printf("mb: decimal: %d \t\tbinary: %b\n", mb, mb) 86 | fmt.Printf("gb: decimal: %d \tbinary: %b\n", gb, gb) 87 | } 88 | ``` 89 | [playground](https://play.golang.org/p/sw-4Kx9q_H) 90 | 91 | You can decide which style you find more readable. 92 | 93 | -------------------------------------------------------------------------------- /section_04_ja/4.1.md: -------------------------------------------------------------------------------- 1 | # セクション 4.1 論理型 2 | 3 | 言語仕様を見て、プログラミング言語の専門用語に精通しておくのは重要な事です。そうしておくと、言語や他の人達との議論でも正確な理解に結びつきます。また、言語のデザインをどうしたかったのかを理解するのはとても大事なことです。[Go言語仕様](https://golang.org/ref/spec)を後で見ていきましょう。 4 | 5 | このセクションでは、Goで異なる型を見ていきます。[論理型](https://golang.org/ref/spec#Boolean_types)を見ていきましょう。 6 | 7 | 論理値は`true`か`false`をとります。[「論理値(boolean)」を検索](https://www.google.ca/search?q=define%3A+boolean&rlz=1C5CHFA_enCA702CA702&oq=define%3A+boolean&aqs=chrome..69i57j69i58.3231j0j7&sourceid=chrome&ie=UTF-8)してみると、「特にコンピューターとエレクトロニクスの分野において、論理値を表現するために使われる記法を意味する」とか「`true`か`false`のどちらかを取るバイナリ値」などと定義されています。 8 | 9 | 論理値はそういうものです。`true`か`false`です。プログラミングにおいてとても重要な役割を持っています。論理値は評価を`true`か`false`落とし込むことができるようにしてくれたり、条件分岐に使えます。何かが`true`の場合にはやることがひとつ決まっており、`false`の場合はそれ以外という感じです。 10 | 11 | このコースの後で、条件分岐やswitch文、if文などシーケンシャルなフローや繰り返しのフローなどを見ていきます。 12 | 13 | 今は、`Boolean`の続きを見ていきましょう。 14 | 15 | Goでは、`bool(論理型)`は型です。`bool`型の`x`を宣言してみましょう。 16 | 17 | ```go 18 | var x bool 19 | ``` 20 | 21 | `var` `x`の_型_は`bool`です。`x`は`bool`_型_の_値を保持_しています。変数`x`を宣言しましたが、、値を割り当てていません。つまり`x`を出力すると、_ゼロ値_が帰ります。`bool`型のゼロ値は`false`です。 22 | 23 | ```go 24 | package main 25 | 26 | import ( 27 | "fmt" 28 | ) 29 | 30 | var x bool 31 | 32 | func main() { 33 | fmt.Println(x) 34 | } 35 | ``` 36 | 37 | [playground](https://play.golang.org/p/QuKLHA2JYG) 38 | 39 | Goでは行末にセミコロンを入れないことを変に思う人もいます。実はセミコロンはコンパイラがこっそり付け加えています。なので、`x = true;`ではなく、`x = true`で大丈夫なのです。Goは_プログラミングを楽すること_に注力しています。効率的なコンパイル、楽なプログラミング、効率的な実行です。 40 | 41 | ```go 42 | package main 43 | 44 | import ( 45 | "fmt" 46 | ) 47 | 48 | var x bool 49 | 50 | func main() { 51 | fmt.Println(x) 52 | x = true 53 | fmt.Println(x) 54 | } 55 | ``` 56 | 57 | 論理値に対しては評価や比較もできますし、返り値に`bool`をとることもできます。[演算子とデリミタ](https://golang.org/ref/spec#Operators_and_Delimiters)を見てみると、二重イコール`==`、小なりイコール`<=`、大なりイコール`>=`、大なり`>`、小なり`<`のような比較のための演算子があるのが分かります。 58 | 59 | 実験してみましょう。短縮形宣言演算子を使い、`a`に`7`、`b`に`47`を割り当ててみて下さい。その後、`a`と`b`を`a == b`として比較してください。 60 | 61 | ```go 62 | package main 63 | 64 | import ( 65 | "fmt" 66 | ) 67 | 68 | var x bool 69 | 70 | func main() { 71 | a := 7 // これを42に変えると、a == bがtrueになります 72 | b := 42 73 | fmt.Println(a == b) // <=, >=, !=, >, <といった演算子で実験してみてください 74 | } 75 | ``` 76 | 77 | [playground](https://play.golang.org/p/NVq6m0_Rzi) 78 | 79 | Goでは二重イコール演算子`==`は同一かどうかを比較します。ひとつのイコール`=`は割り当てに使います。 80 | 81 | [論理型](https://golang.org/ref/spec#Boolean_types)の言語仕様では以下のように書かれています。 82 | 83 | 論理型は前に述べたように`true`か`false`で記述される真偽値を表す。論理型は論理値である。 84 | 85 | -------------------------------------------------------------------------------- /section_04_ja/4.5.md: -------------------------------------------------------------------------------- 1 | # セクション 4.5: 数値システム 2 | 3 | 16進数や10進数、2進数などの数値システムを見ていきましょう。 4 | 5 | 私達が日々生活するのに使っている数値システムは[10進法](https://ja.wikipedia.org/wiki/%E5%8D%81%E9%80%B2%E6%B3%95)ですね。なぜ10がベースなんでしょうか?きっと私達の指が10本だからじゃないでしょうか? 6 | 7 | ||1000万の桁|100万の桁|10万の桁|1万の桁|1000の桁|100の桁|10の桁|1の桁| 8 | |------------|------------|--------|-----------------|-------------|---------|--------|----|----| 9 | |decimal|107|106|105|104|103|102|101|100| 10 | 11 | ||128の桁|64の桁|32の桁|16の桁|8の桁|4の桁|2の桁|1の桁| 12 | |------------|------------|--------|-----------------|-------------|---------|--------|----|----| 13 | |binary|27|26|25|24|23|22|21|20| 14 | 15 | |||||65536の桁|4096の桁|256の桁|16の桁|1の桁| 16 | |------------|------------|--------|-----------------|-------------|---------|--------|----|----| 17 | |hexadecimal|167|166|165|164|163|162|161|160| 18 | 19 | |||||262144の桁|4096の桁|64の桁|1の桁| 20 | |------------|------------|--------|-----------------|-------------|---------|--------|----|----| 21 | |base64|647|646|645|644|643|642|641|640| 22 | 23 | 1、10、100、1000といった桁がテーブルにありますね。10進数ならば、ひとつの桁に10種類の数字が入ります。0~9です。例えば、1の桁に9があり、そこに1を足すと、10の桁に1、1の桁が0になります。10の桁に1、1の桁が0のときのことを10と表現しますね。12のことを言いたかったら10の桁に1、1の桁に2ということになります。この法則を理解すると、2進数や16進数が理解しやすくなります。 24 | 25 | 10進数はどのように動作するのでしょうか?それぞれの桁には1桁の0~9の10種類の数字が入ります。同じように、2進数では1つの桁に1桁の数字が入りますが、入る数は0と1の2種類です。16進数でも1つの桁に1桁の数字が入りますが、入るのは16種類の値です。 26 | 27 | 10から15までの数は2つの文字を使わなければいけないので、16進数では代わりにこの様にします。0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e 28 | 29 | これで、1つの桁に保存できる数は違いますが、10進数と同じように2進数と16進数で数を表現する方法が分かりました。 30 | 31 | それぞれのシステムでの数を見てみましょう。 32 | 33 | |decimal|binary|hexadecimal| 34 | |-------|------|-----------| 35 | |0|0|0| 36 | |1|1|1| 37 | |5|101|5| 38 | |10|1010|a| 39 | |15|1111|e| 40 | |50|110010|32| 41 | |100|1100100|64| 42 | 43 | [10進数を16進数や2進数へ変換する計算機](http://www.rapidtables.com/convert/number/decimal-to-hex.htm) 44 | 45 | ここで2進数ジョークです。「世界には10種類の人間がいる。2進数を理解しているかいないかだ。」 46 | 47 | 42420を表現するためには万の桁に4、千の桁に2、百の桁に4、十の桁に2が必要です。 48 | 49 | |1000万の桁|100万の桁|10万の桁|1万の桁|1000の桁|100の桁|10の桁|1の桁| 50 | |------------|--------|-----------------|-------------|---------|--------|----|----| 51 | |107|106|105|104|103|102|101|100| 52 | | | | | 4 | 2 | 4 | 2 | 0 | 53 | 54 | 42を2進数で表すとどうなるでしょうか? 55 | 56 | |128の桁|64の桁|32の桁|16の桁|8の桁|4の桁|2の桁|1の桁| 57 | |-----|-----------|-----------|--------|------|-----|----|----| 58 | |27|26|25|24|23|22|21|20| 59 | | | | 1 | 0 | 1 | 0 | 1 | 0 | 60 | 61 | 911を16進数で表すと? 62 | 63 | |65536の桁|4096の桁|256の桁|16の桁|1の桁| 64 | |-------|------|----|---|----| 65 | |164|163|162|161|160| 66 | | | | 3 | 8 | F | 67 | 68 | 16進数での数をを10進数(911)にするには、256を3倍し(768)、16を8倍し(128)、15(Fが表現している数)を1倍し(15)、それぞれを足し合わせます。768 + 128 + 15 = 911 69 | 70 | これで10進数、2進数、16進数がどう動作するのか分かりました。Goではどのように扱うのか見ておきましょう。 71 | 72 | ```go 73 | package main 74 | 75 | import ( 76 | "fmt" 77 | ) 78 | 79 | func main() { 80 | s := "H" 81 | fmt.Println(s) 82 | 83 | /* バイト列に変換する */ 84 | bs := []byte(s) 85 | fmt.Println(bs) 86 | 87 | /* bsの0番目をnの値とする */ 88 | n := bs[0] 89 | fmt.Println(n) 90 | 91 | /* nを出力 */ 92 | fmt.Printf("%T\n", n) 93 | 94 | /* 2進数として出力 */ 95 | fmt.Printf("%b\n", n) 96 | 97 | /* 16進数として出力 */ 98 | fmt.Printf("%x\n", n) 99 | 100 | /* 16進数として出力(プレフィックス付き) */ 101 | fmt.Printf("%#X\n", n) 102 | } 103 | ``` 104 | 105 | [playground](https://play.golang.org/p/aruMIxcQFy) 106 | 107 | -------------------------------------------------------------------------------- /section_04_ja/4.6.md: -------------------------------------------------------------------------------- 1 | # セクション 4.6 定数 2 | 3 | `const`(定数)がキーワードかどうか知りたい時、どうやって確かめますか? 4 | 5 | ```go 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | ) 11 | 12 | const 13 | 14 | func main() { 15 | fmt.Println("Hello, playground") 16 | } 17 | ``` 18 | 19 | [The Go Programming Language Specification](https://golang.org/ref/spec)の[Keywords](https://golang.org/ref/spec#Keywords)に答えが載っています。 20 | 21 | ``` 22 | break default func interface select 23 | case defer go map struct 24 | chan else goto package switch 25 | const fallthrough if range type 26 | continue for import return var 27 | ``` 28 | 29 | [Go playground](https://play.golang.org/p/et5Qf-Crsu)でいくつか定数を作ってみましょう。コンパイラが自動的に型を決定してくれます。 30 | 31 | ```go 32 | package main 33 | 34 | import ( 35 | "fmt" 36 | ) 37 | 38 | const a = 42 39 | const b = 42.78 40 | const c = "James Bond" 41 | 42 | func main() { 43 | fmt.Println(a) 44 | fmt.Println(b) 45 | fmt.Println(c) 46 | fmt.Printf("%T\n", a) 47 | fmt.Printf("%T\n", b) 48 | fmt.Printf("%T\n", c) 49 | } 50 | ``` 51 | 52 | `import`文のように、定数を宣言して値を割り当てる方法もあります。 53 | 54 | ```go 55 | package main 56 | 57 | import ( 58 | "fmt" 59 | ) 60 | 61 | const ( 62 | a = 42 63 | b = 42.78 64 | c = "James Bond" 65 | ) 66 | 67 | func main() { 68 | fmt.Println(a) 69 | fmt.Println(b) 70 | fmt.Println(c) 71 | fmt.Printf("%T\n", a) 72 | fmt.Printf("%T\n", b) 73 | fmt.Printf("%T\n", c) 74 | } 75 | ``` 76 | 77 | [playground](https://play.golang.org/p/N3_-plSitG) 78 | 79 | 定数の型を自分で指定することもできます。型が指定されていない定数は_同種の定数_の用に扱われます。コンパイラがどのように型を与えるか決定するため、コンパイラに柔軟性を与えてくれます。型が決定されると、柔軟性はなくなります。 80 | 81 | ```go 82 | package main 83 | 84 | import ( 85 | "fmt" 86 | ) 87 | 88 | const ( 89 | a int = 42 90 | b float32 = 42.78 91 | c string = "James Bond" 92 | ) 93 | 94 | func main() { 95 | fmt.Println(a) 96 | fmt.Println(b) 97 | fmt.Println(c) 98 | fmt.Printf("%T\n", a) 99 | fmt.Printf("%T\n", b) 100 | fmt.Printf("%T\n", c) 101 | } 102 | ``` 103 | 104 | [playground](https://play.golang.org/p/zs-UzDM_Q7) 105 | -------------------------------------------------------------------------------- /section_04_ja/4.7.md: -------------------------------------------------------------------------------- 1 | # Section 4.7: Iota 2 | 3 | [Go Specification](https://golang.org/ref/spec)の[constant declarations](https://golang.org/ref/spec#Constant_declarations)の最後近くで、[iota](https://golang.org/ref/spec#Iota)が`const`の値として割り当てられています。 4 | 5 | `Iota`は定義済みの識別子です。 6 | 7 | ```go 8 | package main 9 | 10 | import ( 11 | "fmt" 12 | ) 13 | 14 | const ( 15 | a = iota 16 | b = iota 17 | c = iota 18 | ) 19 | 20 | func main() { 21 | fmt.Println(a) 22 | fmt.Println(b) 23 | fmt.Println(c) 24 | 25 | fmt.Printf("%T\n", a) 26 | fmt.Printf("%T\n", b) 27 | fmt.Printf("%T\n", c) 28 | } 29 | ``` 30 | 31 | [playground](https://play.golang.org/p/mkQlg_SX4L) 32 | 33 | 値がオートインクリメントしているのが分かります。オートインクリメントする定数をセットするのには、最初だけ`iota`をセットすることだけでも可能です。 34 | 35 | ```go 36 | package main 37 | 38 | import ( 39 | "fmt" 40 | ) 41 | 42 | const ( 43 | a = iota 44 | b 45 | c 46 | ) 47 | 48 | const ( 49 | d = iota 50 | e 51 | f 52 | ) 53 | 54 | func main() { 55 | fmt.Println(a) 56 | fmt.Println(b) 57 | fmt.Println(c) 58 | fmt.Println(d) 59 | fmt.Println(e) 60 | fmt.Println(f) 61 | } 62 | ``` 63 | 64 | こちらのコードではオートインクリメントが定数を宣言しているグループごとにリセットされていることが分かります。 65 | -------------------------------------------------------------------------------- /section_04_ja/4.8.md: -------------------------------------------------------------------------------- 1 | # セクション 4.8: ビットシフト 2 | 3 | セクション[4.5: 数値システム](../section_4/4.5.md)で、16進数などのシステムを学びました。全てが0と1で構成される2進数についても見てきましたね。 4 | 5 | 2進数での1,2,3は1,10,11ですね。そして2進数には[ビットシフト](https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts)という考え方があります。 6 | 7 | `0000 0010`に対してビットシフトを行うと、`0000 0100`になるという感じです。 8 | 9 | [演算子と記号](https://golang.org/ref/spec#Operators_and_punctuation)をビットシフトをするための`<<`と`>>`演算子があります。 10 | 11 | ```go 12 | package main 13 | 14 | import ( 15 | "fmt" 16 | ) 17 | 18 | func main() { 19 | x := 4 20 | fmt.Printf("decimal: %d\t\tbinary: %b\n", x, x) 21 | 22 | y := x << 1 23 | fmt.Printf("decimal: %d\t\tbinary: %b\n", y, y) 24 | 25 | z := x >> 1 26 | fmt.Printf("decimal: %d\t\tbinary: %b\n", z, z) 27 | } 28 | ``` 29 | 30 | The result is: 31 | 32 | ``` 33 | decimal: 4 binary: 100 34 | decimal: 8 binary: 1000 35 | decimal: 2 binary: 10 36 | ``` 37 | 38 | [playground](https://play.golang.org/p/NYOejCbw7Y) 39 | 40 | 1桁をずらすビットシフトをしてみました。`<<`を使うと`100`が`1000`になり、`>>`を使うと`100`は`10`になります。 41 | 42 | kbからmb、そしてgbへとサイズを変えたいときは、10回左シフトをすれば値を得ることができます。 43 | 44 | ```go 45 | package main 46 | 47 | import ( 48 | "fmt" 49 | ) 50 | 51 | func main() { 52 | kb := 1024 53 | mb := 1024 * kb 54 | gb := 1024 * mb 55 | 56 | fmt.Printf("kb: decimal: %d \t\tbinary: %b\n", kb, kb) 57 | fmt.Printf("mb: decimal: %d \t\tbinary: %b\n", mb, mb) 58 | fmt.Printf("gb: decimal: %d \tbinary: %b\n", gb, gb) 59 | } 60 | ``` 61 | 62 | [playground](https://play.golang.org/p/3TA6lwpkfr) 63 | 64 | ``` 65 | kb: decimal: 1024 binary: 10000000000 66 | mb: decimal: 1048576 binary: 100000000000000000000 67 | gb: decimal: 1073741824 binary: 1000000000000000000000000000000 68 | ``` 69 | 70 | ここで[iota](https://golang.org/ref/spec#Iota)を使うこともできます。 71 | 72 | ```go 73 | package main 74 | 75 | import ( 76 | "fmt" 77 | ) 78 | 79 | const ( 80 | _ = iota 81 | // kb = 1024 82 | kb = 1 << (iota * 10) 83 | mb = 1 << (iota * 10) 84 | gb = 1 << (iota * 10) 85 | ) 86 | 87 | func main() { 88 | fmt.Printf("kb: decimal: %d \t\tbinary: %b\n", kb, kb) 89 | fmt.Printf("mb: decimal: %d \t\tbinary: %b\n", mb, mb) 90 | fmt.Printf("gb: decimal: %d \tbinary: %b\n", gb, gb) 91 | } 92 | ``` 93 | 94 | [playground](https://play.golang.org/p/sw-4Kx9q_H) 95 | 96 | どのスタイルが見やすいかで書き方を変えることができます。 97 | -------------------------------------------------------------------------------- /section_05/5.01.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 2 #1 2 | 3 | Write a program that prints a number in decimal, binary, and hex. 4 | 5 | [answer](https://play.golang.org/p/ETreejfgse) 6 | -------------------------------------------------------------------------------- /section_05/5.02.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 2 #2 2 | 3 | Using the following operators, write expressesions and assign their values to variables: 4 | 5 | * `==` 6 | * `<=` 7 | * `>=` 8 | * `!=` 9 | * `<` 10 | * `>` 11 | 12 | [answer](https://play.golang.org/p/dRF6_bk5kD) 13 | -------------------------------------------------------------------------------- /section_05/5.03.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 2 #3 2 | 3 | Create TYPED and UNTYPED constants. Print the values of the constants. 4 | 5 | [answer](https://play.golang.org/p/nZit_5l3fP) 6 | -------------------------------------------------------------------------------- /section_05/5.04.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 2 #4 2 | 3 | Write a program that 4 | * assigns an int to a variable 5 | * prints that int in decimal, binary, and hex 6 | * shifts the bits of that int over 1 position to the left, and assigns that to a variable 7 | * prints that variable in decimal, binary, and hex 8 | 9 | [answer](https://play.golang.org/p/8BKIiPD4Ud) 10 | -------------------------------------------------------------------------------- /section_05/5.05.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 2 #5 2 | 3 | Create a variable of type string using a raw string literal, and then print it. 4 | 5 | [answer](https://play.golang.org/p/wj4t4vcnUa) 6 | -------------------------------------------------------------------------------- /section_05/5.06.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 2 #6 2 | 3 | Using iota, create 4 constants for the last 4 years. Print the constant values. 4 | 5 | [answer](https://play.golang.org/p/ffzD0s7w4m) 6 | -------------------------------------------------------------------------------- /section_05/5.07.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 2 #7 2 | 3 | Take the [quiz](https://docs.google.com/forms/d/e/1FAIpQLSfjhxXjo0r_OsVys58B1lVs35CLPpneVcjiEKTPsLuQs4mftA/viewform). 4 | 5 | [answers](5.7.a.md) 6 | -------------------------------------------------------------------------------- /section_05_ja/5.01.md: -------------------------------------------------------------------------------- 1 | # 練習問題 - レベル 2 #1 2 | 3 | 10進数、2進数、16進数で数を表示するプログラムを書いてください。 4 | 5 | [解答](https://play.golang.org/p/ETreejfgse) 6 | -------------------------------------------------------------------------------- /section_05_ja/5.02.md: -------------------------------------------------------------------------------- 1 | # 練習問題 - レベル 2 #2 2 | 3 | 以下のオペレーターを使い、変数に値を割り当てる式を書いてください。 4 | 5 | * `==` 6 | * `<=` 7 | * `>=` 8 | * `!=` 9 | * `<` 10 | * `>` 11 | 12 | [解答](https://play.golang.org/p/dRF6_bk5kD) 13 | -------------------------------------------------------------------------------- /section_05_ja/5.03.md: -------------------------------------------------------------------------------- 1 | # 練習問題 - レベル 2 #3 2 | 3 | 型を明示/明示していない定数を作り、出力してください。 4 | 5 | [解答](https://play.golang.org/p/nZit_5l3fP) 6 | -------------------------------------------------------------------------------- /section_05_ja/5.04.md: -------------------------------------------------------------------------------- 1 | # 練習問題 - レベル 2 #4 2 | 3 | * 変数にint型の値を割り当て、 4 | * 10進数、2進数、16進数でその値を出力し、 5 | * 左に1つビットシフトし、その値を別の変数に割り当て、 6 | * 10進数、2進数、16進数でその値を出力する 7 | 8 | プログラムを書いてください。 9 | 10 | [解答](https://play.golang.org/p/8BKIiPD4Ud) 11 | -------------------------------------------------------------------------------- /section_05_ja/5.05.md: -------------------------------------------------------------------------------- 1 | # 練習問題 - レベル 2 #5 2 | 3 | string型の変数をraw string literalを使って作り、出力してください。 4 | 5 | [解答](https://play.golang.org/p/hlt9CYDJtg) 6 | -------------------------------------------------------------------------------- /section_05_ja/5.06.md: -------------------------------------------------------------------------------- 1 | # 練習問題 - レベル 2 #6 2 | 3 | iotaを使い、今後の4年の数字を値とする定数を4つ作成し、出力してください。 4 | 5 | [解答](https://play.golang.org/p/ffzD0s7w4m) 6 | -------------------------------------------------------------------------------- /section_05_ja/5.07.md: -------------------------------------------------------------------------------- 1 | # 練習問題 - レベル 2 #7 2 | 3 | [クイズ](https://docs.google.com/forms/d/e/1FAIpQLSfjhxXjo0r_OsVys58B1lVs35CLPpneVcjiEKTPsLuQs4mftA/viewform)をやってみましょう。 4 | 5 | [解答](5.07a.md) 6 | -------------------------------------------------------------------------------- /section_05_ja/5.07a.md: -------------------------------------------------------------------------------- 1 | # プログラミング基礎クイズ 2 | 3 | 1. Goはプログラミングを簡単にすることを推奨している。短縮形宣言演算子を使った場合、型を明示する必要はない。 4 | 5 | - [x] true 6 | - [ ] false 7 | 8 | 2. 自身の言葉で、コンピューターはどう動くか説明してください。 9 | 10 | a.) コンピューターは電気的に動作します。電気にはオンとオフという2つの状態があり、スイッチやサーキットと状態とをコーディングスキーマで組み合わせて操作します。 11 | 12 | 3. コンピューターに関連する場合で、0と1は何を意味しますか? 13 | 14 | a.) 0はオフ、1はオンの短縮系。 15 | 16 | 4. 真偽値で1はtrueですかfalseですか? 17 | 18 | - [x] true 19 | - [ ] false 20 | 21 | 5. 5つの電灯がある場合、いくつのメッセージをエンコードできますか? 22 | 23 | - [ ] 8 24 | - [ ] 16 25 | - [x] 32 26 | - [ ] 64 27 | - [ ] 128 28 | 29 | 6. コンピューターの電源スイッチは0と1でできています。これは0はオフ、1はオンを表していて、オフとオンを切り替えられることを意味している。 30 | 31 | - [x] true 32 | - [ ] false 33 | 34 | 7. Bit(ビット)はbinary digit(バイナリ値)の略である。 35 | 36 | - [x] true 37 | - [ ] false 38 | 39 | 8. オンとオフ、1と0、バイナリ値、ビット、マシン語はコンピューター内では0と1の塊しかなく、それらのオンとオフの切り替えをするのみであるという考え方に基づいている。 40 | 41 | - [x] true 42 | - [ ] false 43 | 44 | 9. サーキット、スイッチ、トランジスタ、ゲートはコンピューター内でオンかオフかの状態を保存することができるものである。 45 | 46 | - [x] true 47 | - [ ] false 48 | 49 | 10. 今日、最も人気のあるテキストコーディングスキーマといえば、 50 | 51 | - [ ] ASCII 52 | - [x] UTF-8 53 | - [ ] JIS 54 | - [ ] W Europe 55 | 56 | 11. 1000バイト = 57 | 58 | - [ ] 1 TB 59 | - [ ] 1 GB 60 | - [ ] 1 MB 61 | - [x] 1 KB 62 | 63 | 12. 1000 GB = 64 | 65 | - [x] 1 TB 66 | - [ ] 1 GB 67 | - [ ] 1 MB 68 | - [ ] 1 KB 69 | 70 | 13. [transistor count](https://en.wikipedia.org/wiki/Transistor_count)を見てください。現在のプロセッサにはいくつのトランジスタがあるか。 71 | 72 | 70億(Xbox One X (Project Scorpio) main SoCの場合) 73 | 74 | 14. ENIACにはいくつのサーキットがありましたか? 75 | 76 | - [ ] 160 77 | - [ ] 1,600 78 | - [x] 16,000 79 | - [ ] 160,000,000 80 | 81 | 15. runeはint32のエイリアスである。 82 | 83 | - [x] true 84 | - [ ] false 85 | 86 | 16. byteはuint8のエイリアスである。 87 | 88 | - [x] true 89 | - [ ] false 90 | 91 | 17. int型を使う場合、コンパイラがint32かint64かを判断して選択する。言い換えると、intには決められたサイズが存在するということである。 92 | 93 | - [x] true 94 | - [ ] false 95 | 96 | 18. だいたいのケースで数値を扱う場合、整数の場合はint、実数の場合はfloat64を使えば良い。 97 | 98 | - [x] true 99 | - [ ] false 100 | 101 | 19. stringはバイトの並びである。 102 | 103 | - [x] true 104 | - [ ] false 105 | 106 | 20. Goのソースコードは常にUTF-8である。 107 | 108 | - [x] true 109 | - [ ] false 110 | 111 | 21. stringはバイトの並びであり、Unicodeのコードポイントを表している、runeと呼ばれるものである。 112 | 113 | - [x] true 114 | - [ ] false 115 | 116 | 22. コーディングスキーマとはなんですか? 117 | 118 | a.) スイッチのオン・オフを表現する0と1の連なり 119 | 120 | 23. 10進数で42は? 121 | 122 | - [x] 42 123 | - [ ] 101010 124 | - [ ] 2A 125 | - [ ] 数値システムのビデオはスキップした 126 | 127 | 24. 2進数で42は? 128 | 129 | - [ ] 42 130 | - [x] 101010 131 | - [ ] 2A 132 | - [ ] 数値システムのビデオはスキップした 133 | 134 | 25. 16進数で42は? 135 | 136 | - [ ] 42 137 | - [ ] 101010 138 | - [x] 2A 139 | - [ ] 数値システムのビデオはスキップした 140 | -------------------------------------------------------------------------------- /section_06/6.01.md: -------------------------------------------------------------------------------- 1 | # Section 6.1 Understanding Control Flow 2 | 3 | [Control flow](https://en.wikipedia.org/wiki/Control_flow) is basically how your computer reads the program. When we read a book, we read it front to back, left to right, top to bottom; that's the _control flow_ of how we read a book. For a computer program, it goes sequentially, until it hits two other kinds of structures. 4 | 5 | One type is a loop (sometimes called an iteration or iterative), it's something that repeats again and again. 6 | 7 | The other stucture is conditional. Conditional is some based on some sort of condition do one thing or another thing. 8 | -------------------------------------------------------------------------------- /section_06/6.02.md: -------------------------------------------------------------------------------- 1 | # Section 6.2 Loop - Init, Condition, Post 2 | 3 | As you're learning Go, a good quick reference is [Go by Example](https://gobyexample.com/). 4 | 5 | For example, here's what it has for [for](https://gobyexample.com/for) 6 | 7 | ```go 8 | package main 9 | 10 | import "fmt" 11 | 12 | func main() { 13 | 14 | i := 1 15 | for i <= 3 { 16 | fmt.Println(i) 17 | i = i + 1 18 | } 19 | 20 | for j := 7; j <= 9; j++ { 21 | fmt.Println(j) 22 | } 23 | 24 | for n := 0; n <= 5; n++ { 25 | if n%2 == 0 { 26 | continue 27 | } 28 | fmt.Println(n) 29 | } 30 | } 31 | ``` 32 | **Note**: There is no `while` in Go. 33 | 34 | The way to create a loop is to start with `for`, and the first thing you put in is an init statement, a condition, and a post, e.g. 35 | 36 | ``` 37 | for init; condition; post { 38 | } 39 | ``` 40 | 41 | Let's try a loop with an init statment initializing a variable `i` with the value `0`, the condition that `i` is less than or equal to `100`, and the post of incrementing `i` by `1` (`i++`). Remember, we can always check the Go spec. In this case, [IncDec statements](https://golang.org/ref/spec#IncDec_statements) has information explaining the `++` and `--` operators. 42 | 43 | ```go 44 | package main 45 | 46 | import ( 47 | "fmt" 48 | ) 49 | 50 | func main() { 51 | for i := 0; i <= 100; i++ { 52 | 53 | } 54 | fmt.Println() 55 | } 56 | ``` 57 | [playground](https://play.golang.org/p/KGaFt09VB0) 58 | 59 | -------------------------------------------------------------------------------- /section_06/6.03.md: -------------------------------------------------------------------------------- 1 | # Section 6.3 Loop - Nested Loops 2 | 3 | Now, we're going to see a loop within a loop. There will be an _outer_ loop, and it will run however many times it runs, and inside that _outer_ loop will be an _inner_ loop, which will loop as many times as it loops _each time_ the outer loop loops. 4 | 5 | For example, if the outer loop loops 10 times, and the inner loop loops 5 times, the outer loop will loop once, then within that loop, the inner loop will loop 5 times, then the outer loop will loop its second time, and within that loop, the inner loop will loop 5 times, and so on... 6 | 7 | This is called nesting a loop; a loop within another loop. We can continue to nest loops within loops, but for now we'll stick with just one lopp within a loop. 8 | 9 | Let's give it a try. 10 | 11 | ```go 12 | say 10 times. ckage main 13 | 14 | import ( 15 | "fmt" 16 | ) 17 | 18 | func main() { 19 | for i := 0; i <= 10; i++ { 20 | for j := 0; j < 3; i++ { 21 | fmt.Printf("The outer loop: %d\t The inner loop: %d\n", i, j) 22 | } 23 | } 24 | } 25 | 26 | ``` 27 | [playground](https://play.golang.org/p/o0YaoYYAC8) 28 | 29 | Here we can see for each iteration of the outer loop, the inner loop prints out `0`, `1`, and `2`. 30 | 31 | Let's break this up and print `i` on the outer loop, and `j` on the inner loop. Try to do this with the output of the inner loop indented 32 | 33 | ```go 34 | package main 35 | 36 | import ( 37 | "fmt" 38 | ) 39 | 40 | func main() { 41 | for i := 0; i <= 10; i++ { 42 | fmt.Printf("Outer loop: %d\n", i) 43 | for j := 0; j < 3; j++ { 44 | fmt.Printf("\tInner loop: %d\n", j) 45 | } 46 | } 47 | } 48 | 49 | ``` 50 | [playground](https://play.golang.org/p/0Gd_NAXNyB) 51 | -------------------------------------------------------------------------------- /section_06/6.04.md: -------------------------------------------------------------------------------- 1 | # Section 6.4 Loop - For Statement 2 | 3 | Let's have a look at [For statements](https://golang.org/ref/spec#For_statements) in the [Go spec](https://golang.org/ref/spec). 4 | 5 | The `for` statement specifies _repeated execution of a block. There are three forms: The iteration may be controlled by a single condition, a `for` claus, or a `range` clause._ 6 | 7 | 8 | ```go 9 | ForStmt = "for" [ Condition | ForClause | RangeClause ] Block . 10 | Condition = Expression . 11 | ``` 12 | 13 | This is not valid Go syntax. It's called [Extended Backus–Naur form](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form) (EBNF). EBNF is used to talk about a computer language. 14 | 15 | ```go 16 | package main 17 | 18 | import ( 19 | "fmt" 20 | ) 21 | 22 | func main() { 23 | x := 1 24 | for x < 10 { 25 | fmt.Println(x) 26 | x++ 27 | } 28 | fmt.Println("done.") 29 | } 30 | ``` 31 | [playground](https://play.golang.org/p/f4L-KA59yQ) 32 | 33 | Continuing through the Go specification on [for statements](https://golang.org/ref/spec#For_statements), we come to "For statements with for clause," which looks like this: 34 | 35 | ```go 36 | for i := 0; i < 10; i++ { 37 | f(i) 38 | } 39 | ``` 40 | 41 | The specification explains, 42 | 43 | _A "for" statement with a ForClause is also controlled by its condition, but additionally it may specify an init and a post statement, such as an assignment, an increment or decrement statement._ 44 | 45 | Then, we have the EBNF explanation 46 | 47 | ``` 48 | ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] . 49 | ``` 50 | 51 | If we relate this to the example above, `i := 0` is the `InitStmt`, `i < 10` is the `Condition`, and `i++` is the `PostStmt`. 52 | 53 | Now, if we continue through the specification, it says 54 | 55 | _The init statement may be a short variable declaration, but the post statement must not. Variables declared by the init statement are re-used in each iteration._ 56 | 57 | This further clarifies that the variable declared in the init statement is used in each iteration of the loop, and that we cannot have a short variable declaration in the post statment. 58 | 59 | Continuing, 60 | 61 | _If non-empty, the init statement is executed once before evaluating the condition for the first iteration; the post statement is executed after each execution of the block (and only if the block was executed)._ 62 | 63 | So, in the example the init statement `i := 0` is executed first. Then the condition `i < 10` is evaluated. _Then_, after the contents within the loop (the block) are executed, the post condition is executed. 64 | 65 | Let's take a look at another way we could iterate through a for loop, and `break` when we are done. 66 | 67 | ```go 68 | package main 69 | 70 | import ( 71 | "fmt" 72 | ) 73 | 74 | func main() { 75 | x := 1 76 | for { 77 | if x > 9 { 78 | break 79 | } 80 | fmt.Println(x) 81 | x++ 82 | } 83 | fmt.Println("done.") 84 | } 85 | ``` 86 | [playground](https://play.golang.org/p/egX34wR3wX) 87 | 88 | That's an example of how we can use `for` on its own (without the init statement, condition, and post statement). 89 | 90 | In addition to the [Go Specification](https://golang.org/ref/spec), another great resource for Go documentation is [Effective Go](https://golang.org/doc/effective_go.html). Let's have a look at what it has to say about [For](https://golang.org/doc/effective_go.html#for) 91 | 92 | _The Go for loop is similar to—but not the same as—C's. It unifies for and while and there is no do-while. There are three forms, only one of which has semicolons._ 93 | 94 | ```go 95 | // Like a C for 96 | for init; condition; post { } 97 | 98 | // Like a C while 99 | for condition { } 100 | 101 | // Like a C for(;;) 102 | for { } 103 | ``` 104 | Notice how Effective Go jumps right to practical uses, whereas the Go Specification has a deeper explanation of the inner-workings. These two resources are excellent for diving into Go. 105 | 106 | -------------------------------------------------------------------------------- /section_06/6.05.md: -------------------------------------------------------------------------------- 1 | # Section 6.5 Loop - Break & Continue 2 | 3 | According to the Go Specification, `break` and `continue` are [keywords](https://golang.org/ref/spec#Keywords). 4 | 5 | ``` 6 | break default func interface select 7 | case defer go map struct 8 | chan else goto package switch 9 | const fallthrough if range type 10 | continue for import return var 11 | ``` 12 | 13 | `break` will _break out_ of a loop. It's a way to stop looping. 14 | 15 | `continue` will move on to the next iteration. Let's see it in action. 16 | 17 | *Aside* dividing and remainders 18 | 19 | ```go 20 | package main 21 | 22 | import ( 23 | "fmt" 24 | ) 25 | 26 | func main() { 27 | x := 83 / 40 28 | y := 83 % 40 29 | fmt.Println(x, y) 30 | } 31 | 32 | ``` 33 | [playground](https://play.golang.org/p/_BNQa7c8d8) 34 | 35 | *note*: `%` (modulo) is an [Arithmetic operator](https://golang.org/ref/spec#Arithmetic_operators) that gives the _remainder_. 36 | 37 | Back to `continue` in action. Let's say we want to iterate from `1` through to `100`, and print out only the even numbers, we can use `for`, `if`, and `continue` 38 | 39 | ```go 40 | package main 41 | 42 | import ( 43 | "fmt" 44 | ) 45 | 46 | func main() { 47 | x := 0 48 | for { 49 | x++ 50 | 51 | // break out of the loop (stop the loop) 52 | // if x is greater than 100 53 | if x > 100 { 54 | break 55 | } 56 | 57 | // continue to the next iteration if the 58 | // remainder of x divided by 2 is not 0 59 | // (if x is not even) 60 | if x%2 != 0 { 61 | continue 62 | } 63 | 64 | fmt.Println(x) 65 | 66 | } 67 | fmt.Println("done.") 68 | } 69 | ``` 70 | [playground](https://play.golang.org/p/aVd3OVLtop) 71 | 72 | -------------------------------------------------------------------------------- /section_06/6.06.md: -------------------------------------------------------------------------------- 1 | # Section 6.6 Loop - Printing ASCII 2 | 3 | ## Mini Hands-On Exercise 4 | 5 | We previously learned how to print the different characters of a string with format printing. Refer to the docmentation for a refresher on the [fmt](https://golang.org/pkg/fmt/) package. 6 | 7 | Loop through the numbers `33` through `122`, and print them out as numbers and text strings. 8 | 9 | *Hint*: Refer to the [ASCII](https://en.wikipedia.org/wiki/ASCII) coding scheme to see the decimal and glyph representations. 10 | 11 | ```go 12 | package main 13 | 14 | import ( 15 | "fmt" 16 | ) 17 | 18 | func main() { 19 | for i := 33; i < 122; i++ { 20 | fmt.Printf("%v\t%#U\n", i, i) 21 | } 22 | } 23 | 24 | ``` 25 | [playground](https://play.golang.org/p/y4OzIKta2M) 26 | 27 | -------------------------------------------------------------------------------- /section_06/6.07.md: -------------------------------------------------------------------------------- 1 | # Section 6.7 Conditional - If Statement 2 | 3 | ## If Statements 4 | 5 | * `bool` 6 | - `true` 7 | - `false` 8 | * the _not_ operator 9 | - `!` 10 | * initialization statement 11 | * `if`/`else` 12 | * `if`/`else` 13 | * `if`/`else` 14 | * `if`/`else if`/.../`else` 15 | 16 | _If statements_ are conditional statements. Remember in control flow, we have sequence, we have iterative, and we also have conditional. Sequence is top to bottom, iterative is looping, and conditional is based upon a condition it will either do one thing or another. 17 | 18 | Let's start with some predeclared constants, `true` and `false` and not true `!true` and not false `!false` 19 | 20 | ```go 21 | package main 22 | 23 | import ( 24 | "fmt" 25 | ) 26 | 27 | func main() { 28 | if true { 29 | fmt.Println("001") 30 | } 31 | 32 | if false { 33 | fmt.Println("002") 34 | } 35 | 36 | if !true { 37 | fmt.Println("003") 38 | } 39 | 40 | if !false { 41 | fmt.Println("004") 42 | } 43 | } 44 | 45 | ``` 46 | [playground](https://play.golang.org/p/Aok8L_OVMo) 47 | 48 | Following through the example above, we see `if true` which will always be true, and will execute. `if false` will always be false, and will not execute. `if !true` is if _not_ true, which is the same as false, and will _not_ execute, while `if !false` is if _not_ false, which will execute. 49 | 50 | Let's try with some more examples using numbers and the not operator `!`: 51 | 52 | ```go 53 | package main 54 | 55 | import ( 56 | "fmt" 57 | ) 58 | 59 | func main() { 60 | if 2 == 2 { 61 | fmt.Println("001") 62 | } 63 | 64 | if 2 != 2 { 65 | fmt.Println("002") 66 | } 67 | 68 | if !(2 == 2) { 69 | fmt.Println("003") 70 | } 71 | 72 | if !(2 != 2) { 73 | fmt.Println("004") 74 | } 75 | } 76 | 77 | ``` 78 | [playground](https://play.golang.org/p/Q1QjvxZzFX) 79 | 80 | In Go, we mostly don't see [semicolons](https://golang.org/doc/effective_go.html#semicolons) at the end of statements in source. Though we do see them in initialization statments. 81 | 82 | So, if we want to have two statements on one line, we can use a semicolon. 83 | ```go 84 | package main 85 | 86 | import ( 87 | "fmt" 88 | ) 89 | 90 | func main() { 91 | fmt.Println("here's a statement"); fmt.Println("something else") 92 | } 93 | 94 | ``` 95 | If you run format, the formatter will put this over two lines. 96 | 97 | One usecase would be initialization of a variable and evaluation, for example `if x := 42; x == 2` will initialize the variable `x` with the value of `42` then will evaluation the expression `x == 2` which is `false` 98 | 99 | ```go 100 | package main 101 | 102 | import ( 103 | "fmt" 104 | ) 105 | 106 | func main() { 107 | if x := 42; x == 2 { 108 | fmt.Println("001") 109 | } 110 | fmt.Println("here's a statement") 111 | fmt.Println("something else") 112 | } 113 | ``` 114 | [playground](https://play.golang.org/p/araiTmOGMJ) 115 | 116 | -------------------------------------------------------------------------------- /section_06/6.08.md: -------------------------------------------------------------------------------- 1 | # Section 6.8 Conditional - If, Else if, Else 2 | 3 | Here's an example of using `if` and `else` 4 | 5 | ```go 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | ) 11 | 12 | func main() { 13 | x := 42 14 | 15 | if x == 40 { 16 | fmt.Println("Our value was 40") 17 | } else { 18 | fmt.Println("Our value was not 40") 19 | } 20 | } 21 | 22 | ``` 23 | [playground](https://play.golang.org/p/o2LQFJxWNR) 24 | 25 | We can also use `else if` as many times as we want within the `if` statement. 26 | 27 | ```go 28 | package main 29 | 30 | import ( 31 | "fmt" 32 | ) 33 | 34 | func main() { 35 | x := 42 36 | if x == 40 { 37 | fmt.Println("Our value was 40") 38 | } else if x == 41 { 39 | fmt.Println("Our value was 41") 40 | } else if x == 42 { 41 | fmt.Println("Our value was 43") 42 | } else if x == 43 { 43 | fmt.Println("Our value was 43") 44 | } else { 45 | fmt.Println("Our value was not 40") 46 | } 47 | } 48 | 49 | ``` 50 | [playground](https://play.golang.org/p/a3jbqR2vXp) 51 | 52 | -------------------------------------------------------------------------------- /section_06/6.09.md: -------------------------------------------------------------------------------- 1 | # Section 6.9 Loop, Conditional, Modulus 2 | 3 | Use the modulo operator `%` and a `for` loop and `if` statement to print out all the even numbers from 1 to 100 4 | 5 | ```go 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | ) 11 | 12 | func main() { 13 | for i := 1; i <= 100; i++ { 14 | if i%2 == 0 { 15 | fmt.Println(i) 16 | } 17 | } 18 | } 19 | 20 | ``` 21 | 22 | [playground](https://play.golang.org/p/JxHol1bZ0f) 23 | 24 | -------------------------------------------------------------------------------- /section_06/6.11.md: -------------------------------------------------------------------------------- 1 | # Section 6.11 Conditional - Switch Statement Documentation 2 | 3 | It's important as a programmer to be comfortable with the documentation, to know what the language specification is, to know what effective Go is, to be able to make sense of the way that the people who wrote these documents wrote them. 4 | 5 | Have a look at the [keywords](https://golang.org/ref/spec#Keywords) 6 | 7 | ``` 8 | break default func interface select 9 | case defer go map struct 10 | chan else goto package switch 11 | const fallthrough if range type 12 | continue for import return var 13 | ``` 14 | So far we have looked at `case`, `break`, `switch`, `fallthrough`, `continue`, `else`, `for`, `if`, `switch`, `var` 15 | 16 | Looking more broadly at the [spec](https://golang.org/ref/spec), we have already covered several of the items, including ... 17 | 18 | The spec is about 50 or 60 pages describing in detail how the Go programming language works. So far, we have covered a fair amount of it already. We are doing great. 19 | 20 | Let's look at the documentation for [switch statements](https://golang.org/ref/spec#Switch_statements). 21 | 22 | ## [Switch statements](https://golang.org/ref/spec#Switch_statements) 23 | 24 | "Switch" statements provide multi-way execution. An expression or type specifier is compared to the "cases" inside the "switch" to determine which branch to execute. 25 | 26 | ``` 27 | SwitchStmt = ExprSwitchStmt | TypeSwitchStmt . 28 | ``` 29 | 30 | There are two forms: expression switches and type switches. In an expression switch, the cases contain expressions that are compared against the value of the switch expression. In a type switch, the cases contain types that are compared against the type of a specially annotated switch expression. The switch expression is evaluated exactly once in a switch statement. 31 | 32 | ### Expression switches 33 | 34 | In an expression switch, the switch expression is evaluated and the case expressions, which need not be constants, are evaluated left-to-right and top-to-bottom; the first one that equals the switch expression triggers execution of the statements of the associated case; the other cases are skipped. If no case matches and there is a "default" case, its statements are executed. There can be at most one default case and it may appear anywhere in the "switch" statement. [A missing switch expression is equivalent to the boolean value true](https://play.golang.org/p/gM8k01Mnfn). 35 | 36 | ``` 37 | ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" . 38 | ExprCaseClause = ExprSwitchCase ":" StatementList . 39 | ExprSwitchCase = "case" ExpressionList | "default" . 40 | ``` 41 | 42 | [Effective Go](https://golang.org/doc/effective_go.html) has this to say about [switch](https://golang.org/doc/effective_go.html#switch) 43 | 44 | Go's switch is more general than C's. The expressions need not be constants or even integers, the cases are evaluated top to bottom until a match is found, and if the switch has no expression it switches on true. It's therefore possible—and idiomatic—to write an if-else-if-else chain as a switch. 45 | 46 | ```go 47 | package main 48 | 49 | import ( 50 | "fmt" 51 | ) 52 | 53 | func main() { 54 | fmt.Println(unhex('E')) 55 | } 56 | 57 | func unhex(c byte) byte { 58 | switch { 59 | case '0' <= c && c <= '9': 60 | return c - '0' 61 | case 'a' <= c && c <= 'f': 62 | return c - 'a' + 10 63 | case 'A' <= c && c <= 'F': 64 | return c - 'A' + 10 65 | } 66 | return 0 67 | } 68 | 69 | ``` 70 | 71 | There is no automatic fall through, but cases can be presented in comma-separated lists. 72 | 73 | ```go 74 | func shouldEscape(c byte) bool { 75 | switch c { 76 | case ' ', '?', '&', '=', '#', '+', '%': 77 | return true 78 | } 79 | return false 80 | } 81 | 82 | ``` 83 | 84 | [Effective Go](https://golang.org/doc/effective_go.html) and the Go [Spec](https://golang.org/ref/spec) are useful tools to make use of while learning Go. 85 | 86 | -------------------------------------------------------------------------------- /section_06/6.12.md: -------------------------------------------------------------------------------- 1 | # Section 6.12 Conditional Logic Operators 2 | 3 | Try to think through the following conditionals before trying them out the playgroud. Will they evaluate to true or false? 4 | 5 | ```go 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | ) 11 | 12 | func main() { 13 | fmt.Println(true && true) 14 | fmt.Println(true && false) 15 | fmt.Println(true || true) 16 | fmt.Println(true || false) 17 | fmt.Println(!true) 18 | } 19 | 20 | ``` 21 | [playground](https://play.golang.org/p/ukFrlC66uv) 22 | 23 | `&&` will return `true` if both sides evaluate to `true`, otherwise it will return `false`. 24 | 25 | `||` will return `true` if either side evaluates to `true`. 26 | 27 | `!` returns the opposite 28 | 29 | Try [some examples](https://play.golang.org/p/cZEfXSIIDO) for yourself. 30 | 31 | ```go 32 | package main 33 | 34 | import ( 35 | "fmt" 36 | ) 37 | 38 | func main() { 39 | fmt.Printf("true && true\t %v\n", true && true) 40 | fmt.Printf("true && false\t %v\n", true && false) 41 | fmt.Printf("true || true\t %v\n", true || true) 42 | fmt.Printf("true || false\t %v\n", true || false) 43 | fmt.Printf("!true\t %v\n", !true) 44 | } 45 | ``` 46 | [playground](https://play.golang.org/p/SRCpC1-aXf) 47 | 48 | -------------------------------------------------------------------------------- /section_07/7.01.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 3 #1 2 | 3 | Print every number from 1 to 10,000 4 | 5 | [answer](https://play.golang.org/p/Y7Tr8DqVuZ) 6 | 7 | -------------------------------------------------------------------------------- /section_07/7.02.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 3 #2 2 | 3 | Print every rune code point of hte uppercase alphabet three times. Your output should look like this: 4 | 5 | 65 6 | U+0041 'A' 7 | U+0041 'A' 8 | U+0041 'A' 9 | 10 | 66 11 | U+0042 'B' 12 | U+0042 'B' 13 | U+0042 'B' 14 | 15 | ... through the rest of the characters. 16 | 17 | [answer](https://play.golang.org/p/-DRL4e60jD) 18 | 19 | -------------------------------------------------------------------------------- /section_07/7.03.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 3 #3 2 | 3 | Create a for loop using this syntax 4 | 5 | * for condition {} 6 | 7 | Have it print out the years you have been alive. 8 | 9 | [answer](https://play.golang.org/p/tnyqBPJ-i5) 10 | -------------------------------------------------------------------------------- /section_07/7.04.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 3 #4 2 | 3 | Create a for loop using this syntax 4 | 5 | * for {} 6 | 7 | Have it print out hte years you have been alive. 8 | 9 | [answer](https://play.golang.org/p/ujil0hqEmK) 10 | 11 | -------------------------------------------------------------------------------- /section_07/7.05.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 3 #5 2 | 3 | Print out the remainder modulus which is found for each number between 10 and 100 when it is divided by 4. 4 | 5 | [answer](https://play.golang.org/p/ohfJOW9euy) 6 | -------------------------------------------------------------------------------- /section_07/7.06.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 3 #6 2 | 3 | Create a program that shows the "if statement" in action. 4 | 5 | [answer](https://play.golang.org/p/DpZ_FLfn5s) 6 | 7 | -------------------------------------------------------------------------------- /section_07/7.07.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 3 #7 2 | 3 | Building on the previos exervice, create a program that uses else if and else. 4 | 5 | [answer](https://play.golang.org/p/6eIoEuhYmL) 6 | -------------------------------------------------------------------------------- /section_07/7.08.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 3 #8 2 | 3 | Create a program that uses a switch statement with no switch expression specified. 4 | 5 | [answer](https://play.golang.org/p/69hNAjsopW) 6 | 7 | -------------------------------------------------------------------------------- /section_07/7.09.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 3 #9 2 | 3 | Create a program that uses a switch statement with the switch expression specified as a variable of TYPE string with the IDENTIFIER "favSport" 4 | 5 | [answer](https://play.golang.org/p/LY5FUKRHWM) 6 | 7 | -------------------------------------------------------------------------------- /section_07/7.10.md: -------------------------------------------------------------------------------- 1 | # Hands on Exercises - Level 3 #10 2 | 3 | Write down what these print 4 | 5 | * fmt.Println(true && true) 6 | * fmt.Println(true && false) 7 | * fmt.Println(true || true) 8 | * fmt.Println(true || false) 9 | * fmt.Println(!true) 10 | 11 | [answer](https://play.golang.org/p/TG4Rp6sOCe) 12 | 13 | --------------------------------------------------------------------------------