User defined function types in Go (Golang)
len() zurück, wenn ihr eine UTF-8-kodierte Zeichenkette übergeben wird?Length of string in Go (Golang).
do { ... } while i < 5
for _,c := range "hello" { ... }
for i := 1; i < 5; i++ { ... }
for i < 5 { ... }
Erklärung: Go hat nur for-Schleifen
values := []int{1, 1, 2}
values.append(3)
values.insert(3, 3)
append(values, 3)
values = append(values, 3)
Erklärung: Slices in GO sind unveränderlich, sodass der Aufruf von append den Slice nicht modifiziert
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 nie initialisiert wurde.[] ausgeben."[" +nil+"]" auch nil ist.GlobalFlag nie initialisiert wurde.myVar zugänglich, wenn sie außerhalb aller Funktionen in einer Datei im Paket myPackage innerhalb des Moduls myModule deklariert ist?myPackage aufgerufen werden, nicht im Rest von myModule.myModule importiert.myModule aufgerufen werden.myModule aufgerufen werden, solange sie myPackage importierenErklärung: Um die Variable außerhalb von myPackage verfügbar zu machen, ändern Sie den Namen in MyVar.
Siehe auch ein Beispiel für Exported names in der Tour of Go.
go test, dass es die auszuführenden Tests ausgeben soll?go testgo test -xgo test --verbosego test -v{0, 0} aus. Wie können Sie es reparieren?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.Decoder verwendendata übergebenX und Y exportieren (großschreiben)sync.Mutex während er gesperrt ist?Mutexint und einen Mutex übergeben und zählen, wenn sie zurückkehren.select-Anweisung iterieren.sync.WaitGroupErklärung: Genau dafür ist sync.WaitGroup konzipiert - Use sync.WaitGroup in Golang
time.After in einer select-Anweisung?select-Anweisung, bis die Zeit verstrichen ist.Hinweis: Es blockiert
selectnicht und blockiert auch nicht die anderen Kanäle.
func Add(a, b int) int {
return a + b
}
A
// Calculate a + b
// - a: int
// - b: int
// - returns: int
func Add(a, b int) int {
return a + b
}
B
// Does a + b
func Add(a, b int) int {
return a + b
}
C
// Add returns the sum of a and b
func Add(a, b int) int {
return a + b
}
D
// returns the sum of a and b
func Add(a, b int) int {
return a + b
}
Erklärung: Der Dokumentationsblock sollte mit einem Funktionsnamen beginnen
var, um i := myVal.(int)? zu kompilieren?myVal muss ein Integer-Typ sein, wie int, int64, int32, etc.myVal muss als int assertiert werden können.myVal muss ein Interface sein.myVal muss ein numerischer Typ sein, wie float64 oder int64.Erklärung: Diese Art der Typumwandlung (mit .(type)) wird nur auf Interfaces angewendet.
//go:build windows“Go-Versionen 1.16 und früher verwendeten eine andere Syntax für Build-Einschränkungen mit einem “// +build” Präfix. Der gofmt-Befehl fügt eine äquivalente //go:build Einschränkung hinzu, wenn er auf die ältere Syntax stößt.”
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 lauten?switch-Anweisung _ ihren eigenen lexikalischen Block. Jede case-Anweisung _ einen zusätzlichen lexikalischen 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-Funktion?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.Sub() und Time.Add() des time-Pakets?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 innerhalb eines 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?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)Erklärung: Es ist weder log.ERROR noch log.Error() in log package in Go definiert; log.Print() Argumente werden wie bei fmt.Print() behandelt; log.Printf() Argumente werden wie bei fmt.Printf() behandelt.
go test Befehl als Testdateien?test beginnentest enthalten_test.go enden_test.go endench := 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)
The Go Programming Language Specification “Receive operator”, Relevant excerpt from the article:
A receive operation on a closed channel can always proceed immediately, yielding the element type’s zero value after any previously sent values have been received.
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.
Hello Gopher! ausgeben wird?go(fmt.Println("Hello Gopher!"))go func() { fmt.Println("Hello Gopher!") }go fmt.Println("Hello Gopher!")Go fmt.Println("Hello Gopher!")String() string implementierenfunc 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 Befehl des Go-Compilers?sql, json, yaml und Schalter --schema und --objects bereit, um relevanten Code zu generieren._generate.go enden, und kompiliert und führt dann jede dieser Dateien einzeln aus.//go:generate Kommentaren und führt für jeden solchen Kommentar den Terminal-Befehl aus, den er angibt.mocks und tests, um relevante .go Quelldateien zu generieren.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) direkt nach wg.Wait() hinzu.make(chan, int) hinzu, z. B. make(chan int, 5).WaitGroup Aufrufe, z. B. alle Zeilen, die mit wg beginnen.wg.Add(1) zu einer Zeile direkt vor 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 auf die Marshal Funktion zu?encoding.json.Marshalencoding/json.MarshalMarshaljson.Marshalcontext.Context vervollständigen würden, um ein drei-Sekunden-Timeout für diesen HTTP-Client bei einer GET-Anfrage zu implementieren?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)
}
ctx.SetTimeout(3*time.Second)
req.AttachContext(ctx)
ctx, cancel = context.WithTimeout(ctx, 3*time.Second); defer cancel()
req = req.WithContext(ctx)
ctx, cancel = context.WithTimeout(ctx, 3*time.Second); defer cancel() #2: req.AttachContext(ctx)
ctx.SetTimeout(3*time.Second)
req = req.WithContext(ctx)
let Default := new Client()
public default = &Client()
var Default = &Client{}
export default := new Client{}
{Master Chief Spartan Protagonist Halo} aus. Wie würden Sie es so ändern, dass es stattdessen Master Chief - a Spartan - is the Protagonist of Halo ausgibt?package main
import "fmt"
type Character struct{
Name string
Class string
Role string
Game string
}
func main() {
mc := Character{
Name: "Master Chief",
Class: "Spartan",
Role: "Protagonist",
Game: "Halo",
}
fmt.Println(mc)
}
A
// Replace
// fmt.Println(mc)
// with this:
fmt.Printf("(?P<Name>) - a (?P<Class>) - is the (?P<Role>) of (?P<Game>)", mc)
B
// Replace
// fmt.Println(mc)
// with this:
fmt.Println(mc, func(c Character) string {
return c. Name + " - a " + c.Class + " - is the " + c.Role + " of " + c.Game
})
C
// add this to the package `main`
func (c Character) String() string {
return fmt.Sprintf("%s - a %s - is the %s of %s", c.Name, c.Class, c.Role,c.Game)
}
D
// add this to the package `main`
func (c Character) OnPrint() {
fmt.Println(" - a - is the of ")
}
Append() Methode für Clients implementieren?package main
type Client struct {
Name string
}
type Clients struct {
clients []*Client
}
func main() {
c:= &Clients{clients.make([]*Client,0)}
c.Append(&Client{Name: "LinkedIn API})
}
A
func (cc *Clients) Append(c *Client) {
cc.clients = append(cc.clients, c)
}
B
func (cc *Clients) Append(c *Client) {
cc.append(c)
}
C
func (cc Clients) Append(c Client) {
cc.clients = append(cc.clients, c)
}
Append()-Methode für Clients implementieren?package main
type Client struct {
Name string
}
type Clients struct {
clients []*Client
}
func main() {
c:= &Clients{clients.make([]*Client,0)}
c.Append(&Client{Name: "LinkedIn API})
}
A
func (cc *Clients) Append(c *Client) {
cc.clients = append(cc.clients, c)
}
B
func (cc *Clients) Append(c *Client) {
cc.append(c)
}
C
func (cc Clients) Append(c Client) {
cc.clients = append(cc.clients, c)
}
D
func (cc *Clients) Append(c Client) {
cc.clients.append(c)
}
panic() erholen, ohne dass Ihr Programm fehlschlägt, wobei davon ausgegangen wird, dass Ihre Antwort im selben Scope ausgeführt wird, in dem Ihr Funktionsaufruf den Panic erfährt?Umhüllen Sie den Funktionsaufruf in eine anonyme Funktion mit einem Rückgabetyp von panic und denken Sie daran, die anonyme Funktion durch das Suffix () aufzurufen, und untersuchen Sie dann die zurückgegebene panic-Instanz, um den Fehler zu behandeln.
Verwenden Sie try{ ... }, um den Code, der die Funktion aufruft, zu umschließen und behandeln Sie dann den Fehler innerhalb des catch{ ... }.
Verwenden Sie defer func { ... }() vor dem fehlerhaften Funktionsaufruf und behandeln Sie die Panic innerhalb der anonymen Funktion.
Präfixieren Sie den Funktionsaufruf mit @, um die Panic als error-Wert zurückzugeben, und behandeln Sie den Fehler dann so, wie Sie einen von einer Funktion zurückgegebenen error behandeln würden.
var n int
fmt.Println (n)
In Go erhält eine deklarierte, aber nicht initialisierte Variable den Zero Value ihres Typs. Für Ganzzahlen wie
nist der Zero Value 0.
String() string eines benutzerdefinierten Typs aufzurufen?In Go wird der Verb
%sverwendet, um einen String zu formatieren. Bei einem benutzerdefinierten Typ mit definierterString()-Methode wird diese automatisch aufgerufen, und ihr Rückgabewert wird im formatierten String verwendet.
time.Now().Format(layout)?Laut Dokumentation repräsentieren die Werte 1 und 01 den aktuellen Monat.
each layout string is a representation of the time stamp,
Jan 2 15:04:05 2006 MST
An easy way to remember this value is that it holds, when presented in this order, the values (lined up with the elements above):
1 2 3 4 5 6 -7
Namespace das Interface JSONConverter implementieren muss? Es wird angenommen, dass die Antwort im selben Package enthalten ist, in dem Namespace deklariert ist.Diese Syntax erstellt eine Variable
_vom TypJSONConverterund weist ihr den Wert(*Namespace)(nil)zu. Dadurch wird sichergestellt, dassNamespacedas InterfaceJSONConvertererfüllt, indem überprüft wird, dass es einer Variablen vom TypJSONConverterzugewiesen werden kann.
implements deklarieren, dass ihre Instanzen überall verwendet werden können, wo eine Variable, ein Parameter und/oder ein Rückgabewert für das deklarierte Interface typisiert ist.In Go erfüllt ein Typ automatisch ein Interface, wenn er alle Methoden dieses Interfaces implementiert. Es ist nicht erforderlich, explizit zu deklarieren, dass eine Struktur ein Interface mit einem speziellen Schlüsselwort implementiert.
===[Output]================
1: &{GameId:1 Title:Wolfenstein YearReleased:1992}
2: &{GameId:2 Title:Doom YearReleased:1993}
3: &{GameId:3 Title:Quake YearReleased:1996}
===[main.go]================
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
)
type Game struct {
GameId int
Title string
YearReleased int
}
func main() {
conn, err := sql.Open("mysql",
"john_carmack:agiftw!@tcp(localhost:3306)/idsoftware")
if err != nil {
panic(err)
}
defer func() { _ = conn.Close() }()
results, err := conn.Query("SELECT game_id,title,year_released FROM games;")
if err != nil {
panic(err)
}
defer func() { _ = results.Close() }()
// #1 <=== What goes here?
for results.Next() {
var g Game
// #2 <=== What goes here?
if err != nil {
panic(err)
}
// #3 <=== What goes here?
}
for i, g := range games {
fmt.Printf("%d: %+v\n", i, g)
}
}
#1: games := make([]*Game, results.RowsAffected())
#2: g, err = results.Fetch()
#3: games[results.Index()] = &g
#1: games := []Game{}
#2: g, err = results.Fetch()
#3: games = append(games,g)
#1: games := map[int]Game{}
#2: err = results.Scan(&g)
#3: games[g.GameId] = g
#1: games := make(map[int]*Game, 0)
#2: err = results.Scan(&g.GameId, &g.Title, &g.YearReleased)
#3: games[g.GameId] = &g
im Unterverzeichnis /test/ dieses Packages gespeichert sein
Funktionen, die einen testing.Tester-Parameter akzeptieren
Funktionen schreiben, deren Namen ^Subtest entsprechen
testing.AssertionFailed aufrufen
auf _test.go enden
Funktionsnamen, die ^Test[A-Z] entsprechen
t.Run() aufrufen
t.Errorf() aufrufen
mit test_ beginnen
Funktionen, die [a-z]Test$ entsprechen
testing.Subtest() aufrufen
testing.Assert() erlauben, seine Assertion fehlschlagen zu lassen
im Wurzelunterverzeichnis /test/ des Projekts gespeichert sein
Funktionen akzeptieren einen testing.Test-Parameter
Closures an testing.AddSubtest() übergeben
einen error aus der Funktion zurückgeben
rune ein Alias?Relevanter Auszug aus dem Artikel:
Der Begriff
runeist in Go ein Alias für den Typint32, damit Programme klar machen können, wenn ein ganzzahliger Wert einen Code Point darstellt.
:= verwenden, um mehreren Variablen zuzuweisen? Zum Beispiel:x, err := myFunc()
cpu.pprof im Browser ansehen?interface{} den Wert nil?nil ist. (true)nil gesetzt.nil sein.Wenn eine String-Variable alloziert, aber nicht zugewiesen wurde, ist ihr Standardwert der leere String “”. In Go erhalten nicht initialisierte String-Variablen den Zero Value ihres Typs, der für Strings der leere String ist.
Die eingebaute Funktion zum Anhalten des Programms ist
panic(). Ein Aufruf vonpanic()löst eine Panic aus und beendet den normalen Ausführungsfluss. Wenn sie nicht abgefangen wird, beendet das Programm.
a,b := 1, 2
b,c:= 3, 4
fmt.Println(a, b, c)
| [ ] |
funclambdafunc()anonymousErläuterung: Sie können inline dort definiert werden, wo sie verwendet werden, was mehr Flexibilität in der Codeorganisation bietet.
functionName(){}call functionName()func(){}()execute func(){}all named types not built-in to Go, such as type Example int but not int, type Example struct{...} but not struct, etc.only types named struct, map, and slice, such as type Example struct{…}only types named struct, such as type Example struct{...}all typesMethoden können für jeden benannten Typ definiert werden, der kein Built-in-Typ ist. Wenn Sie mit einer Typdeklaration einen neuen Typ erstellen, wird er zu einem benannten Typ, und Sie können spezifische Methoden dafür definieren. An Built-in-Typen wie
int,stringetc. können jedoch keine Methoden direkt angefügt werden. reference