From b0e6aeb3b013cb7c5c55a775c6dc7af8ae5626ec Mon Sep 17 00:00:00 2001 From: Sebastian Macke Date: Sun, 13 Oct 2024 16:34:14 +0200 Subject: [PATCH] Prepare lecture basics --- docs/01-1-About.slide | 2 +- docs/02-Go Programming - Basics.slide | 155 ++++++++++++++---- docs/exercises/Exercise2.2.md | 11 +- go.mod | 12 +- go.sum | 11 ++ src/basics/index/index.go | 1 - src/basics/pointers/pointer/pointer.go | 34 ++-- src/basics/stringer/stringer.go | 17 ++ src/basics/types/maps/maps.go | 37 ++--- src/basics/types/maps/maps2.go | 36 ++++ src/basics/types/slices/old/slices.go | 3 + .../types/slices/{ => old}/slices_test.go | 2 +- src/basics/types/slices/slices.go | 26 ++- 13 files changed, 256 insertions(+), 91 deletions(-) create mode 100644 src/basics/stringer/stringer.go create mode 100644 src/basics/types/maps/maps2.go create mode 100644 src/basics/types/slices/old/slices.go rename src/basics/types/slices/{ => old}/slices_test.go (98%) diff --git a/docs/01-1-About.slide b/docs/01-1-About.slide index 7d36eaf..5a953e1 100644 --- a/docs/01-1-About.slide +++ b/docs/01-1-About.slide @@ -1,5 +1,5 @@ Welcome -Concepts of Programming Languages - TH Rosenheim - WS 2023/2024 +Concepts of Programming Languages - TH Rosenheim - WS 2024/2025 Tags: go, golang, programming, master Sebastian Macke diff --git a/docs/02-Go Programming - Basics.slide b/docs/02-Go Programming - Basics.slide index a93034d..e6e38de 100644 --- a/docs/02-Go Programming - Basics.slide +++ b/docs/02-Go Programming - Basics.slide @@ -2,14 +2,19 @@ Go Programming - Basics Concepts of Programming Languages Tags: go, programming, master -Sebastian Macke, Stefan Langer +Sebastian Macke Rosenheim Technical University Sebastian.Macke@th-rosenheim.de https://www.qaware.de -* Organisational matters -- Some missing students last time -- Questions +* Last Lecture: + +- Introduction +- The many ways to characterize a language +- Go Introduction + +- Characteristics of a Successful Language +-- Miro Board .... * Characteristics of a Successful Language (Suggestion) - Simplicity and readability (Small instruction set and easy syntax) @@ -20,7 +25,6 @@ https://www.qaware.de - Good support and documentation (public compilers, tutorials, community, IDE) - Orthogonality - * What is an Orthogonal language - Def 1: A language is orthogonal if its features are built upon a small, mutually *independent* set of primitive operations. @@ -32,6 +36,13 @@ https://www.qaware.de : http://www.javawenti.com/?post=39930 +* Orthogonal Design by an example + +- Type System is a "feature" +- Functions are a "feature" +- Types are used in functions as parameters or return values. +- Orthogonal would mean, that the type system is independent of the functions. +- E. g. The behaviour of the type is not influenced by a function or vice-versa. * Types VS. Functions (Non-Orthogonal Design by example) - E. g. in C, the type system is not orthogonal to the function system. @@ -126,9 +137,16 @@ https://www.qaware.de - The entry point for Go executable is always the function main in package main (main.main) - New packages need a new directory and can then be referenced - *Public* *functions* *begin* *with* *a* *capital* *letter* +: - Package import names are hierarchical +: - Package names are not hierarchical! : neues Verzeichnis mit Paket anlegen und zeigen, wie man von main darauf zugreift +* Primitive Types +- Basic building block of a programming language +- They are not defined in terms of other data types +- Usually designed with the CPU architecture in mind + * Primitive Types .html snippets/basic_types.html - In Go the type of a variable is behind the name! @@ -159,13 +177,13 @@ Languages differ of how serious they handle the type - statically typed: type checking at compile time - dynamically typed: type checking at runtime -: Frage an Studenten: bitte ausfüllen. - Go uses a strong typing system. But why? -* Weak typing vs. Strong typing II +: Frage an Studenten: bitte ausfüllen. -.image img/02-typing.png 450 _ +: * Weak typing vs. Strong typing II + +: .image img/02-typing.png 450 _ * Where implicit type conversion in C goes wrong @@ -180,6 +198,9 @@ Go uses a strong typing system. But why? return 0; } +Also: Change int to char + + : https://www.onlinegdb.com/online_c_compiler : change int to char @@ -187,27 +208,36 @@ Go uses a strong typing system. But why? .image ./img/banana_meme.png 400 _ : https://jsconsole.com/ -: 4 + "7" -: 4 * "7" +: 4 + "7" -> conversion to strings +: "4" + 7 +: 4 - "7" -> conversion to number +: "4" - "7" -> conversion to number +: "" - "" => 0 +: 4 * "7" -> conversion to numbers : 2 + true : false - 3 -: 0 == "" -> true : "" - "" => 0 +: 0 == "" -> true : new Array() == false : {} + {} => "[object Object][object Object]" (typeof ({} + {}) is string) : {} + [] => 0 : {} + {} + [] => "NaN" as string : ({} + {}) + [] => "" : {} + ({} + []) => NaN as number +: ({} + {} + []) => ("[object Object][object Object]") +: ("NaN") => "NaN" : 0 > null => false : 0 >= null => true : 0 === null => false : [1,2,3] + [4,5,6] => "1,2,34,5,6" : http://www.jsfuck.com/ -: .... -: ("NaN") => "NaN" -: ({} + {} +[]) => ("[object Object][object Object]") +: parseInt(1) : parseInt(0.0000001) +: "" + 0.00000001 + +* Dynamically typing in Python + +- Demo with state of the art AI libs * Strong typing in Go @@ -217,19 +247,43 @@ Go uses a strong typing system. But why? - The compiler will complain if you try to compare different types. - You have to do the type conversion explicitly. -* Golang - some details +* The many ways of variable declarations in Go + + var foo int // default value zero + foo = 32 -* Go has a dynamic type: any + var foo int = 32 + + var foo = 32 + + foo := 32 // infers (guesses) the type definition of type int + + foo := int(32) + + foo, ok := 32, true // foo is an int 32, ok is a boolean with value true + + +* Go has also a dynamic type: any .play ../src/basics/dynamic/main.go /START OMIT/,/END OMIT/ : - The downcast is safe (== dynamic_cast in C++ or cast in Java) + +* Type systems in other languages + +.image img/02-typing.png 450 _ +- Miro board .... + +* Golang - some details + + * Maps - Maps are Go's built-in associative data type (sometimes called hashes or dicts in other languages). -.play ../src/basics/types/maps/maps.go /START OMIT/,/END OMIT/ +.play ../src/basics/types/maps/maps.go +: /START OMIT/,/END OMIT/ * Arrays and Slices - Arrays have a fixed length and can not be resized @@ -238,20 +292,9 @@ Go uses a strong typing system. But why? - The underlying array grows automatically (if needed) - Both have a length and a capacity: What does that mean? - arr := [5]int{1, 2, 3, 4, 5} - - s := arr[0:2] - - fmt.Println(len(s), cap(s)) // ==> 2, 5 - - s = append(s, 8) - s = append(s, 9) - s = append(s, 10) - s = append(s, 11) - - fmt.Println(len(s), cap(s)) // ==> 6, 10 +* Arrays and Slices -: slicecap zeigen +.play ../src/basics/types/slices/slices.go * Functions and Control Structures: Example Palindrome @@ -276,6 +319,12 @@ Go uses a strong typing system. But why? pos, ch := range runes +: * Functions and Control Structures: Example String Reverse (UTF-8) + +: Bad example of usage of multiple parameters +: .code ../src/basics/types/strings/strings.go /Reverse/,/End OMIT/ + + * Functions and Control Structures: Example Palindrome (Reverse) .code ../src/basics/palindrome/palindrome.go /IsPalindrome3/,/END3 OMIT/ - Strings, arrays are compared in Go with == @@ -354,11 +403,46 @@ A pointer is a variable which contains a memory address * Exercise 2.1 .link https://github.com/s-macke/concepts-of-programming-languages/blob/master/docs/exercises/Exercise2.1.md +* Pointer arithmetic is a "DON'T DO" in Go! +- There is some unsafe pointer arithmetic as in C / C ++ + +.play ../src/basics/pointers/unsafe/main.go /func main/, + +- Because of garbage collection anything can happen here! Even more unsafe than in C! + +: In C wäre die Anpassung des Pointers nur y++ + +: * What are references + +: References are kind of safe pointers. In different languages they have slighty different meanings and properties. + +: - They all have in common, that they don't allow pointer arithmetic. +: - Usually no dererefence with * necessary +: - Normally strongly typed +: - In C++ a reference must be initialized at creation and can never be null. In this way C++ ist stricter than Java +: - In Java because of Garbage Collection the reference might not be direct pointer to the object. +: - In Go, nil is the zero value for pointers, interfaces, maps, slices, channels and function types, representing an uninitialized value. + * Maps and Slices - Example Book Index -.code ../src/basics/index/index.go /Page/,/END OMIT/ + +Types can be defined with the keyword "type" + + // Page contains an array of words. + type Page []string + + // Book is an array of pages. + type Book []Page + + // Index contains a list of pages for each word in a book. + type Index map[string][]int + + // MakeIndex generates an index structure + func MakeIndex(book Book) Index { + .... + } * Stringer Interface -.code ../src/basics/interfaces/interfaces.go +.play ../src/basics/stringer/stringer.go * The Flag API simplifies Command Line Utilities .play ../src/basics/flags/main.go /import/,/END OMIT/ @@ -367,6 +451,10 @@ A pointer is a variable which contains a memory address : vergleich https://stackoverflow.com/questions/7341683/parsing-arguments-to-a-java-command-line-program +: * public static void +: - Thoughts about language design: +: .link https://www.youtube.com/watch?v=5kj5ApnhPAE + * Summary - Compiled (cross compiler for OS: Mac, Windows, Linux and CPU: ARM, x86 + Amd64) @@ -375,7 +463,6 @@ A pointer is a variable which contains a memory address - Simple (less keywords like C - 25/32) and Orthogonal - Strong type system with runtime support (Reflection, Dynamic Types) - : - Object-oriented, Functional, Parallel, Modular and Versioned * Exercise 2.2 diff --git a/docs/exercises/Exercise2.2.md b/docs/exercises/Exercise2.2.md index 3df21b3..924935c 100644 --- a/docs/exercises/Exercise2.2.md +++ b/docs/exercises/Exercise2.2.md @@ -8,7 +8,7 @@ A Book Index is an inverted index which lists all pages a word occurs in a book. Write a program which generates an inverted index out of an array of book pages. Each Page contains an array of words. -- Define custom types for Book, Page and Index +- USe the "type" keyword to define custom types for Book, Page and Index. - Make sure the Stringer() interface is implemented for Book and Index to make them printable More details about the Stringer interface: https://tour.golang.org/methods/17 The stringer interface will be explained in more detail in the next lecture. @@ -21,7 +21,7 @@ Each Page contains an array of words. # Usage of the Library functions and error handling Write a program "find" that searches the filesystem recursively from a given path and regex expression. -1. Use the flag library to provide the following parameters +1. Use the flag library (https://tour.golang.org/methods/17) to provide the following parameters ``` Usage of find: -path string @@ -29,11 +29,10 @@ Write a program "find" that searches the filesystem recursively from a given pat -regex string path (default ".*") ``` - -3. Use the ioutil.ReadDir (https://pkg.go.dev/io/ioutil@go1.17.2#ReadDir) function to list the contents of a given directory. Check each file for the given regex with the +2. Use the ioutil.ReadDir (https://pkg.go.dev/io/ioutil@go1.17.2#ReadDir) function to list the contents of a given directory. Check each file for the given regex with the "regexp.MatchString" (https://pkg.go.dev/regexp#MatchString) function and print its path+name on the screen. -4. Either use "panic" or "log.Fatal" for error handling. -5. Run through directories recursively +3. Either use "panic" or "log.Fatal" for error handling. +4. Run through directories recursively # Question Go doesn't support Exceptions but uses multiple return values of which one can be the error information. diff --git a/go.mod b/go.mod index cd4781d..6fed0b8 100644 --- a/go.mod +++ b/go.mod @@ -1,15 +1,17 @@ module github.com/s-macke/concepts-of-programming-languages -go 1.21 +go 1.22.0 + +toolchain go1.23.0 require ( github.com/antlr/antlr4/runtime/Go/antlr v0.0.0-20210930093333-01de314d7883 github.com/coreos/etcd v3.3.26+incompatible github.com/fogleman/gg v1.3.0 github.com/jacobsa/fuse v0.0.0-20210904154839-95fc8d118111 - golang.org/x/net v0.5.0 // indirect - golang.org/x/sys v0.4.0 - golang.org/x/text v0.6.0 // indirect + golang.org/x/net v0.30.0 // indirect + golang.org/x/sys v0.26.0 + golang.org/x/text v0.19.0 // indirect google.golang.org/genproto v0.0.0-20211001223012-bfb93cce50d9 // indirect google.golang.org/grpc v1.41.0 google.golang.org/protobuf v1.27.1 @@ -21,6 +23,8 @@ require ( github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect github.com/golang/protobuf v1.5.2 // indirect + github.com/yuin/goldmark v1.4.13 // indirect golang.org/x/exp v0.0.0-20220328175248-053ad81199eb // indirect golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d // indirect + golang.org/x/tools v0.26.0 // indirect ) diff --git a/go.sum b/go.sum index 87a4e37..5f9dfd5 100644 --- a/go.sum +++ b/go.sum @@ -55,6 +55,7 @@ github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/jacobsa/fuse v0.0.0-20210904154839-95fc8d118111 h1:x35u3++Oj2CXNVqUSPdf/DX8QbfbVKb+T0fKzGIHlWY= @@ -82,6 +83,8 @@ github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5Cc github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -110,6 +113,8 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.5.0 h1:GyT4nK/YDHSqa1c4753ouYCDajOYKTja9Xb/OHtgvSw= golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws= +golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4= +golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -129,6 +134,8 @@ golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18= golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo= +golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -136,6 +143,8 @@ golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.6.0 h1:3XmdazWV+ubf7QgHSTWeykHOci5oeekaGJBLkrkaw4k= golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM= +golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= @@ -144,6 +153,8 @@ golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBn golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ= +golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/src/basics/index/index.go b/src/basics/index/index.go index 6684756..6b5317b 100644 --- a/src/basics/index/index.go +++ b/src/basics/index/index.go @@ -39,7 +39,6 @@ func (idx Index) String() string { // MakePage constructs a page from a string array. func MakePage(words []string) Page { - var err error page := words return page } diff --git a/src/basics/pointers/pointer/pointer.go b/src/basics/pointers/pointer/pointer.go index 10bee79..f30add7 100644 --- a/src/basics/pointers/pointer/pointer.go +++ b/src/basics/pointers/pointer/pointer.go @@ -3,18 +3,24 @@ package main import "fmt" func main() { - var num int = 42 - ptr := &num - - fmt.Println("Value of num:", num) - // Expected Output: Value of num: 42 - - fmt.Println("Address of num:", &num) - // Expected Output: Address of num: 0xSOME_MEMORY_ADDRESS (this will vary every run) - - fmt.Println("Value via pointer:", *ptr) - // Expected Output: Value via pointer: 42 - - fmt.Println("Address stored in ptr:", ptr) - // Expected Output: Address stored in ptr: 0xSOME_MEMORY_ADDRESS (same as address of num) + num := 42 // implicit type "int" with value 42 + ptr := &num // implicit type of "pointer to type int points to num" + //var num int = 42 // explicit type definition + //var ptr *int = &num // explicit type definition + + fmt.Println("Value of num:", num) + // Expected Output: Value of num: 42 + + fmt.Println("Address of num:", &num) + // Expected Output: Address of num: 0xSOME_MEMORY_ADDRESS (this will vary every run) + + fmt.Println("Address stored in ptr:", ptr) + // Expected Output: Address stored in ptr: 0xSOME_MEMORY_ADDRESS (same as address of num) + + fmt.Println("Value via pointer:", *ptr) + // Expected Output: Value via pointer: 42 + + *ptr = 43 + fmt.Println("Value of num:", num) + // Expected output: New value in num = 43 } diff --git a/src/basics/stringer/stringer.go b/src/basics/stringer/stringer.go new file mode 100644 index 0000000..63e2222 --- /dev/null +++ b/src/basics/stringer/stringer.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" + "strings" +) + +type Page []string + +func (p Page) String() string { + return strings.Join(p, "\n") +} + +func main() { + page := Page{"This is the first paragraph", "This is the second paragraph"} + fmt.Println(page) +} diff --git a/src/basics/types/maps/maps.go b/src/basics/types/maps/maps.go index 7df4b6e..eae7aea 100644 --- a/src/basics/types/maps/maps.go +++ b/src/basics/types/maps/maps.go @@ -1,35 +1,18 @@ package main -import ( - "fmt" - "strings" -) +import "fmt" -// START OMIT -func countWords(input string) map[string]int { +func main() { + m := make(map[string]string) // Initialize an empty map + m["foo"] = "bar" // insert a key-value pair into map - // Split the string into words using whitespace as a delimiter - words := strings.Fields(input) + value, ok := m["asd"] // check if key is present, return parameters can be ignored with "_" + fmt.Println(ok, value) // returns false, value is just an empty string "" - // Initialize an empty map to store word counts - wordCounts := make(map[string]int) + value, ok = m["foo"] // returns true, value contains "bar" + fmt.Println(ok, value) - // Iterate over the words and update the count in the map - for _, word := range words { - word = strings.ToLower(word) // Convert word to lowercase to ensure case-insensitivity - wordCounts[word]++ // Increment the count for this word + for k, v := range m { + fmt.Println(k, v) } - - return wordCounts } -// END OMIT - -func main() { - text := "If it is to be it is up to me to delegate" - wordCounts := countWords(text) - - fmt.Println("Word counts:") - for word, count := range wordCounts { - fmt.Printf("%s: %d\n", word, count) - } -} \ No newline at end of file diff --git a/src/basics/types/maps/maps2.go b/src/basics/types/maps/maps2.go new file mode 100644 index 0000000..d5b8be6 --- /dev/null +++ b/src/basics/types/maps/maps2.go @@ -0,0 +1,36 @@ +package main + +import ( + "fmt" + "strings" +) + +// START OMIT +func countWords(input string) map[string]int { + + // Split the string into words using whitespace as a delimiter + words := strings.Fields(input) + + // Initialize an empty map to store word counts + wordCounts := make(map[string]int) + + // Iterate over the words and update the count in the map + for _, word := range words { + word = strings.ToLower(word) // Convert word to lowercase to ensure case-insensitivity + wordCounts[word]++ // Increment the count for this word + } + + return wordCounts +} + +// END OMIT + +func main() { + text := "If it is to be it is up to me to delegate" + wordCounts := countWords(text) + + fmt.Println("Word counts:") + for word, count := range wordCounts { + fmt.Printf("%s: %d\n", word, count) + } +} diff --git a/src/basics/types/slices/old/slices.go b/src/basics/types/slices/old/slices.go new file mode 100644 index 0000000..edc845c --- /dev/null +++ b/src/basics/types/slices/old/slices.go @@ -0,0 +1,3 @@ +// Copyright 2018 Johannes Weigend +// Licensed under the Apache License, Version 2.0 +package old diff --git a/src/basics/types/slices/slices_test.go b/src/basics/types/slices/old/slices_test.go similarity index 98% rename from src/basics/types/slices/slices_test.go rename to src/basics/types/slices/old/slices_test.go index b250e89..1fd15e0 100644 --- a/src/basics/types/slices/slices_test.go +++ b/src/basics/types/slices/old/slices_test.go @@ -1,6 +1,6 @@ // Copyright 2018 Johannes Weigend // Licensed under the Apache License, Version 2.0 -package slices +package old import ( "fmt" diff --git a/src/basics/types/slices/slices.go b/src/basics/types/slices/slices.go index 677c555..80e475e 100644 --- a/src/basics/types/slices/slices.go +++ b/src/basics/types/slices/slices.go @@ -1,3 +1,23 @@ -// Copyright 2018 Johannes Weigend -// Licensed under the Apache License, Version 2.0 -package slices +package main + +import "fmt" + +func main() { + arr := [5]int{1, 2, 3, 4, 5} // create fixed array + fmt.Println(arr) + + s := arr[0:2] // create a slice out of the array. Otherwise via "make([2]int)" for a new array + fmt.Println(s) + + fmt.Println(len(s), cap(s)) // ==> 2, 5 + s[0] = 100 // a slice is just a reference + fmt.Println(arr) + + s = append(s, 8) + s = append(s, 9) + s = append(s, 10) + s = append(s, 11) + + fmt.Println(len(s), cap(s)) // ==> 6, 10 + fmt.Println(arr) +}