User defined function types in Go (Golang)
len() function return if passed a UTF-8 encoded string?Length of string in Go (Golang).
do { ... } while i < 5for _,c := range "hello" { ... }for i := 1; i < 5; i++ { ... }for i < 5 { ... }Explanation: Go has only for-loops
values := []int{1, 1, 2}
values.append(3)values.insert(3, 3)append(values, 3)values = append(values, 3)Explanation: slices in GO are immutable, so calling append does not modify the slice
Read?const (
Write = iota
Read
Execute
)
import "github/gin-gonic/gin"import "https://github.com/gin-gonic/gin"import "../template"import "github.com/gin-gonic/gin"package main
var GlobalFlag string
func main() {
print("["+GlobalFlag+"]")
}
GlobalFlag was never initialized.[]."[" +nil+"]" is also nil.GlobalFlag was never initialized.myVar accessible if it is declared outside of any functions in a file in package myPackage located inside module myModule?myPackage, not the rest of myModule.myModule.myModule.myModule as long as they import myPackageExplanation: to make the variable available outside of myPackage change the name to MyVar.
See also an example of Exported names in the Tour of Go.
go test to print out the tests it is running?go testgo test -xgo test --verbosego test -v{0, 0}. How can you fix it?type Point struct {
x int
y int
}
func main() {
data := []byte(`{"x":1, "y": 2}`)
var p Point
if err := json.Unmarshal(data, &p); err != nil {
fmt.Println("error: ", err)
} else {
fmt.Println(p)
}
}
json.DecoderdataX and Y exported (uppercase)sync.Mutex block while it is locked?Mutexint and Mutex to each and count when they return.select statement.sync.WaitGroupExplanation: this is exactly what sync.WaitGroup is designed for - Use sync.WaitGroup in Golang
time.After in a select statement?select statement until the time has passed.Note: it doesn’t block
selectand does not block other channels.
func Add(a, b int) {
return a + b
}
A
// Calculate a + b
// - a: int
// - b: int
// - returns: int
func Add(a, b int) {
return a + b
}
B
// Does a + b
func Add(a, b int) {
return a + b
}
C
// Add returns the sum of a and b
func Add(a, b int) {
return a + b
}
D
// returns the sum of a and b
func Add(a, b int) {
return a + b
}
Explanation: documentation block should start with a function name
var to compile this i := myVal.(int)?myVal must be an integer type, such as int, int64, int32, etc.myVal must be able to be asserted as an int.myVal must be an interface.myVal must be a numeric type, such as float64 or int64.Explanation: This kind of type casting (using .(type)) is used on interfaces only.
//go:build windows
“Go versions 1.16 and earlier used a different syntax for build constraints, with a “// +build” prefix. The gofmt command will add an equivalent //go:build constraint when encountering the older syntax.”
data := "A group of Owls is called a parliament"
resp, err := http.Post("https://httpbin.org/post", "text/plain", []byte(data))resp, err := http.Post("https://httpbin.org/post", "text/plain", data)resp, err := http.Post("https://httpbin.org/post", "text/plain", strings.NewReader(data))resp, err := http.Post("https://httpbin.org/post", "text/plain", &data)Save() error?switch statement _ its own lexical block. Each case statement _ an additional lexical blockGo Language Core technology (Volume one) 1.5-scope
Relevant excerpt from the article:
The second if statement is nested inside the first, so a variable declared in the first if statement is visible to the second if statement. There are similar rules in switch: Each case has its own lexical block in addition to the conditional lexical block.
Unmarshal function?Relevant excerpt from the article:
To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. By default, object keys which don’t have a corresponding struct field are ignored (see Decoder.DisallowUnknownFields for an alternative).
time package’s Time.Sub() and Time.Add() methods?Example of Recover Function in Go (Golang)
Relevant excerpt from the article:
Recover is useful only when called inside deferred functions. Executing a call to recover inside a deferred function stops the panicking sequence by restoring normal execution and retrieves the error message passed to the panic function call. If recover is called outside the deferred function, it will not stop a panicking sequence.
println(message)log.New(os.Stderr, "", 0).Println(message)fmt.Errorf("%s\n", message)fmt.Fprintln(os.Stderr, message)go mod edit -replace example.com/greetings=../greetings.go test allgo run --allgo test .go test ./...Relevant excerpt from the article:
Relative patterns are also allowed, like “go test ./…” to test all subdirectories.
Relevant excerpt from the article:
In short, Go source code is UTF-8, so the source code for the string literal is UTF-8 text.
Relevant excerpt from the article:
Package encoding defines an interface for character encodings, such as Shift JIS and Windows 1252, that can convert to and from UTF-8.
t.Fatal different inside a t.Run?
Fatalis equivalent toLogfollowed byFailNow.
Logformats its arguments using default formatting, analogous toPrintln, and records the text in the error log.
FailNowmarks the function as having failed and stops its execution by callingruntime.Goexit(which then runs all deferred calls in the current goroutine). Execution will continue at the next test or benchmark.FailNowmust be called from the goroutine running the test or benchmark function, not from other goroutines created during the test. CallingFailNowdoes not stop those other goroutines.
Runrunsfas a subtest oftcalled name. It runsfin a separate goroutine and blocks untilfreturns or callst.Parallelto become a parallel test. Run reports whetherfsucceeded (or at least did not fail before callingt.Parallel).
Run may be called simultaneously from multiple goroutines, but all such calls must return before the outer test function for t returns.
log.Fatal do?Example of func Fatal in Go (Golang)
Relevant excerpt from the article:
Fatalis equivalent toPrint()followed by a call toos.Exit(1).
Relevant excerpt from the article:
Year: "2006" "06"
Month: "Jan" "January" "01" "1"
Day of the week: "Mon" "Monday"
Day of the month: "2" "_2" "02"
Day of the year: "__2" "002"
Hour: "15" "3" "03" (PM or AM)
Minute: "4" "04"
Second: "5" "05"
AM/PM mark: "PM"
log.Error(err)log.Printf("error: %v", err)log.Printf(log.ERROR, err)log.Print("error: %v", err)Explanation: There is defined neither log.ERROR, nor log.Error() in log package in Go; log.Print() arguments are handled in the manner of fmt.Print(); log.Printf() arguments are handled in the manner of fmt.Printf().
go test command recognize as test files?testtest_test.go_test.goch := make(chan int)
ch <- 7
val := <-ch
fmt.Println(val)
Go Playground share, output:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
/tmp/sandbox2282523250/prog.go:7 +0x37
Program exited.
ch := make(chan int)
close(ch)
val := <-ch
fmt.Println(val)
Go Playground share, output:
0
Program exited.
var stocks map[string]float64 // stock -> price
price := stocks["MSFT"]
fmt.Printf("%f\n", price)
Go Playground share, output:
0.000000
Program exited.
print Hello Gopher!?go(fmt.Println("Hello Gopher!"))go func() { fmt.Println("Hello Gopher!") }go fmt.Println("Hello Gopher!")Go fmt.Println("Hello Gopher!")String() stringfunc findUser(ctx context.Context, login string) (*User, error) {
ch := make(chan *User)
go func() {
ch <- findUserInDB(login)
}()
select {
case user := <-ch:
return user, nil
case <-ctx.Done():
return nil, fmt.Errorf("timeout")
}
}
Relevant excerpt from the article:
The simplest way to resolve this leak is to change the channel from an unbuffered channel to a buffered channel with a capacity of 1. Now in the timeout case, after the receiver has moved on, the Goroutine will complete its send by placing the *User value in the channel then it will return.
var i int8 = 120
i += 10
fmt.Println(i)
Go Playground example, output:
-126
Program exited.
func worker(m Message) Result
go func() {
r := worker(m)
ch <- r
}
go func() {
r := worker(m)
r -> ch
} ()
go func() {
r := worker(m)
ch <- r
} ()
go ch <- worker(m)
package os
type FilePermission int
type userID int
generate command of the Go compiler do?sql, json, yaml, and switches --schema and --objects to generate relevant code._generate.go, and then compiles and runs each of these files individually.//go:generate comments, and for each such comment runs the terminal command it specifies.mocks and tests to generate relevant .go source files.Generate Go files by processing source
time.Now().Add(90)time.Now() + (90 * time.Minute)time.Now() + 90time.Now().Add(90 * time.Minute)close(ch) immediately after wg.Wait().make(chan, int), e.g. make(chan int, 5).WaitGroup calls, e.g. all lines that start with wg.wg.Add(1) to a line immediately before wg.Wait().Relevant excerpt from the article:
The simplest way to resolve this leak is to change the channel from an unbuffered channel to a buffered channel with a capacity of 1. Now in the timeout case, after the receiver has moved on, the Goroutine will complete its send by placing the *User value in the channel then it will return.
encoding/json, how will you access the Marshal function?encoding.json.Marshalencoding/json.MarshalMarshaljson.Marshalcontext.Context to implement a three-second timeout for this HTTP client making a GET request?package main
import (
"context"
"fmt"
"net/http"
)
func main() {
var cancel context.CancelFunc
ctx := context.Background()
// #1: <=== What should go here?
req, _ := http.NewRequest(http.MethodGet,
"https://linkedin.com",
nil)
// #2: <=== What should go here?
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
fmt.Println("Response received, status code:",
res.StatusCode)
}
#1: ctx.SetTimeout(3*time.Second) #2: req.AttachContext(ctx)#1: ctx, cancel = context.WithTimeout(ctx, 3*time.Second); defer cancel() #2: req = req.WithContext(ctx)#1: ctx, cancel = context.WithTimeout(ctx, 3*time.Second); defer cancel() #2: req.AttachContext(ctx)#1: ctx.SetTimeout(3*time.Second) #2: req = req.WithContext(ctx)