initial
This commit is contained in:
commit
74ae93a96e
1 changed files with 94691 additions and 0 deletions
263
joplin notion extension/Web Development/Go/Basics 2.md
Normal file
263
joplin notion extension/Web Development/Go/Basics 2.md
Normal file
|
|
@ -0,0 +1,263 @@
|
|||
Basics 2
|
||||
|
||||
Conditions
|
||||
|
||||
if/else if/else are same its just that brackets surrounding conditions are not required. switch case is similar too with extra functionality like multi case
|
||||
|
||||
```go
|
||||
func main() {
|
||||
day := 5
|
||||
|
||||
switch day {
|
||||
case 1,3,5:
|
||||
fmt.Println("Odd weekday")
|
||||
case 2,4:
|
||||
fmt.Println("Even weekday")
|
||||
case 6,7:
|
||||
fmt.Println("Weekend")
|
||||
default:
|
||||
fmt.Println("Invalid day of day number")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
### Loops
|
||||
like in other language. for iteraing over elements of arrays,slice and map range keyword can be used too. it gives index and value respectively.
|
||||
index may not be used so blank identifiers can be used which is like a black hole. And even if it is used then it means those values wont be used later so it will still generate error so in that case blank identifier can be used too
|
||||
|
||||
|
||||
```go
|
||||
adj := [2]string{"Big", "Tasty"}
|
||||
fruits := [...]string{"Apple", "Orange"}
|
||||
|
||||
for i := 0; i < len(adj); i++ {
|
||||
for j := 0; j < len(fruits); j++ {
|
||||
if adj[i] == "Big" {
|
||||
|
||||
fmt.Println("Big mentioned")
|
||||
}
|
||||
fmt.Println(adj[i], fruits[j])
|
||||
}
|
||||
}
|
||||
|
||||
for i, val := range adj {
|
||||
for j, val2 := range fruits {
|
||||
if val == "Big" {
|
||||
|
||||
fmt.Println("Big mentioned")
|
||||
}
|
||||
fmt.Println(val, val2)
|
||||
// blank identifers
|
||||
_, _ = i, j
|
||||
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Extras
|
||||
- go functions if needed to be used in other packages then it needed to be capitalized so using Run() instead of run().
|
||||
|
||||
|
||||
|
||||
random number
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Random integer between 0 and 99
|
||||
num := rand.IntN(100)
|
||||
fmt.Println("Integer (0-99):", num)
|
||||
|
||||
// Random float64 between 0.0 and 1.0
|
||||
floatNum := rand.Float64()
|
||||
fmt.Println("Float (0.0-1.0):", floatNum)
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
||||
also
|
||||
```go
|
||||
|
||||
f,err := os.Open(path)
|
||||
|
||||
if err!=nil{
|
||||
return err
|
||||
}
|
||||
|
||||
defer f.Close()
|
||||
|
||||
scanner:= bufio.NewScanner(f)
|
||||
|
||||
|
||||
```
|
||||
NewScanner accepts io.Reader but os.Open outputs *os.File. due to inferfaces handled implicitly so need to 'implement interface' like in java
|
||||
|
||||
|
||||
|
||||
**structs**
|
||||
```go
|
||||
type Message struct {
|
||||
Id string `json:"id"`
|
||||
CreatedTimestamp int64 `json:"createdTimestamp"`
|
||||
Type int `json:"type"`
|
||||
Content string `json:"content"`
|
||||
Reference struct {
|
||||
MessageId string `json:"messageId"`
|
||||
} `json:"reference"`
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
or if null is expected and empty struct is not fine then simply use pointer struct
|
||||
```go
|
||||
type Message struct {
|
||||
Id string `json:"id"`
|
||||
CreatedTimestamp int64 `json:"createdTimestamp"`
|
||||
Type int `json:"type"`
|
||||
Content string `json:"content"`
|
||||
Reference *struct {
|
||||
MessageId string `json:"messageId"`
|
||||
} `json:"reference"`
|
||||
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
optional fields in struct
|
||||
|
||||
```go
|
||||
type User struct {
|
||||
Name string `json:"name"`
|
||||
Age *int `json:"age,omitempty"` // Optional
|
||||
Active *bool `json:"active,omitempty"` // Optional
|
||||
}
|
||||
```
|
||||
|
||||
for array of struct if we need to distinguish nil and empty slice before go 1.24 then
|
||||
```go
|
||||
Items *[]Product `json:"items,omitempty"`
|
||||
```
|
||||
|
||||
otherwise following will be fine
|
||||
```go
|
||||
Items []Product `json:"items,omitempty"`
|
||||
```
|
||||
|
||||
|
||||
parsing fields of multtiple types
|
||||
https://stackoverflow.com/questions/56394456/unmarshal-json-field-is-int-or-string
|
||||
|
||||
also
|
||||
https://go.dev/play/p/XnQRS8H0tKE
|
||||
```go
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func foo(x any) {
|
||||
switch v := x.(type) {
|
||||
case int:
|
||||
fmt.Printf("math: x + 2 == %d\n", v+2)
|
||||
case string:
|
||||
fmt.Printf("string: x + def == %s\n", v+"def")
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
var x any = 5
|
||||
foo(x)
|
||||
x = "abc"
|
||||
foo(x)
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
and maybe with reflects(not recommended)
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
func checkEquality(data any) {
|
||||
switch reflect.TypeOf(data).Kind() {
|
||||
case reflect.Int:
|
||||
if data == 1 {
|
||||
fmt.Println("It is equal to 1")
|
||||
} else {
|
||||
fmt.Println("It is not equal to 1")
|
||||
}
|
||||
case reflect.String:
|
||||
if data == "one" {
|
||||
fmt.Println("It is equal to one")
|
||||
} else {
|
||||
fmt.Println("It is not equal to one")
|
||||
}
|
||||
default:
|
||||
fmt.Println("Not a string nor an int")
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
checkEquality("one")
|
||||
checkEquality(1)
|
||||
checkEquality(true)
|
||||
checkEquality(34)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
**error handling**
|
||||
|
||||
|
||||
```go
|
||||
|
||||
err:= json.Unmarshal(data, &config)
|
||||
if err != nil {
|
||||
fmt.Println("Error in reading json")
|
||||
os.Exit(1)
|
||||
}
|
||||
```
|
||||
|
||||
short form of above
|
||||
```go
|
||||
if err:= json.Unmarshal(data, &config); err!=nil{
|
||||
// code for handling error
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
also for equivalent ry catch possibility
|
||||
|
||||
```go
|
||||
func riskyBlock() (err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err = fmt.Errorf("recovered from panic: %v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
// --- your code here ---
|
||||
x := 10 / 0 // panics
|
||||
fmt.Println(x) // never reached
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
if err := riskyBlock(); err != nil {
|
||||
fmt.Println("Error:", err)
|
||||
}
|
||||
fmt.Println("Program continues")
|
||||
}
|
||||
```
|
||||
Loading…
Reference in a new issue