linkedin-skill-assessments-quizzes

Go (Programming Language)

Q1. Was benötigen Sie, damit zwei Funktionen vom gleichen Typ sind?

User defined function types in Go (Golang)

Q2. Was gibt die Funktion len() zurück, wenn ihr eine UTF-8-kodierte Zeichenkette übergeben wird?

Length of string in Go (Golang).

Q3. Welches ist KEINE gültige Schleifenkonstruktion in Go?

      do { ... } while i < 5
      for _,c := range "hello" { ... }
      for i := 1; i < 5; i++ { ... }
      for i < 5 { ... }

Erklärung: Go hat nur for-Schleifen

Q4. Wie fügen Sie die Zahl 3 rechts hinzu?

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

Q5. Was ist der Wert von Read?

const (
  Write = iota
  Read
  Execute
)

IOTA in Go (Golang)

Q6. Welches ist die EINZIGE gültige Import-Anweisung in Go?

      import "github/gin-gonic/gin"
      import "https://github.com/gin-gonic/gin"
      import "../template"
      import "github.com/gin-gonic/gin"

Import in GoLang

Q7. Was würde passieren, wenn Sie versuchen würden, dieses Go-Programm zu kompilieren und auszuführen?

package main
var GlobalFlag string
func main() {
  print("["+GlobalFlag+"]")
}
  1. variables in Go haben Anfangswerte. Für String-Typ ist es eine leere Zeichenkette.
  2. Go Playground

Q8. Von wo ist die Variable myVar zugänglich, wenn sie außerhalb aller Funktionen in einer Datei im Paket myPackage innerhalb des Moduls myModule deklariert ist?

Erklä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.

Q9. Wie sagen Sie go test, dass es die auszuführenden Tests ausgeben soll?

test package

Q10. Dieser Code gab {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)
  }
}
  1. How to Parse JSON in Golang?
  2. Go Playground

Q11. Was blockiert ein sync.Mutex während er gesperrt ist?

  1. Mutex in GoLang, sync.Mutex sperrt, sodass immer nur eine Goroutine gleichzeitig auf die gesperrte Variable zugreifen kann.
  2. sync.Mutex

Q12. Was ist eine idiomatische Möglichkeit, die Ausführung des aktuellen Gültigkeitsbereichs anzuhalten, bis eine beliebige Anzahl von Goroutinen zurückgekehrt ist?

Erklärung: Genau dafür ist sync.WaitGroup konzipiert - Use sync.WaitGroup in Golang

Q13. Was ist ein Nebeneffekt der Verwendung von time.After in einer select-Anweisung?

Hinweis: Es blockiert select nicht und blockiert auch nicht die anderen Kanäle.

  1. time.After() Function in Golang With Examples
  2. How can I use ‘time.After’ and ‘default’ in Golang?
  3. Go Playground example

Q14. Wofür wird die select-Anweisung verwendet?

Select statement in GoLang

Q15. Wie sollten Sie diese Funktion gemäß dem Go-Dokumentationsstandard dokumentieren?

func Add(a, b int) int {
        return a + b
}

Erklärung: Der Dokumentationsblock sollte mit einem Funktionsnamen beginnen

Comments in Go

Q16. Welche Einschränkung gibt es für den Typ von var, um i := myVal.(int)? zu kompilieren?

Erklärung: Diese Art der Typumwandlung (mit .(type)) wird nur auf Interfaces angewendet.

  1. this example
  2. Primitive types are type-casted differently
  3. Go Playground
  4. Type assertions

Q17. Was ist ein Channel?

Channels

Q18. Wie können Sie eine Datei so erstellen, dass sie nur unter Windows kompiliert wird?

  1. How to use conditional compilation with the go build tool, Oct 2013
  2. go commands Build constraints

//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.”

Q19. Wie übergeben Sie dies korrekt als Body einer HTTP-POST-Anfrage?

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)
  1. net/http#Client.Post
  2. http.Post Golang example

Q20. Wie sollte der idiomatische Name für ein Interface mit einer einzelnen Methode und der Signatur Save() error lauten?

Effective Go, Interface names

Q21. Eine switch-Anweisung _ ihren eigenen lexikalischen Block. Jede case-Anweisung _ einen zusätzlichen lexikalischen Block

Go 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.

Q22. Was ist die Standard-Groß-/Kleinschreibung der JSON Unmarshal-Funktion?

encoding/json#Unmarshal

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).

Q23. Was ist der Unterschied zwischen den Methoden Time.Sub() und Time.Add() des time-Pakets?

  1. time#Time.Add
  2. time#Time.Sub

Q24. Was ist das Risiko der Verwendung mehrerer Feld-Tags in einer einzelnen Struktur?

  1. Example Code / b29r0fUD1cp
  2. How To Use Struct Tags in Go

Q25. Wo ist die eingebaute recover-Methode nützlich?

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.

Q26. Welche Option sendet keine Ausgabe nach Standardfehler?

  1. func println: writes the result to standard error.
  2. func New: func New(out io.Writer, prefix string, flag int) *Logger; the out variable sets the destination to which log data will be written.
  3. func Errorf: Errorf formats according to a format specifier and returns the string as a value.
  4. func Fprintln: func Fprintln(w io.Writer, a …any) (n int, err error); Fprintln formats using the default formats for its operands and writes to w.

Q27. Wie können Sie Go mitteilen, ein Paket von einem anderen Speicherort zu importieren?

  1. Call your code from another module: chapter 5., go mod edit -replace example.com/greetings=../greetings.
  2. go.mod replace directive

Q28. Wenn sich Ihr aktuelles Arbeitsverzeichnis auf der obersten Ebene Ihres Projekts befindet, welcher Befehl führt alle Test-Pakete aus?

  1. Example of testing in Go (Golang)
  2. Example of cmd in Go (Golang)

Relevant excerpt from the article:

Relative patterns are also allowed, like “go test ./…” to test all subdirectories.

Q29. Welche Kodierungen können Sie in einer Zeichenkette verwenden?

  1. Strings, bytes, runes and characters in Go

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.

  1. Example of encoding in Go (Golang)

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.

Q30. Wie unterscheidet sich das Verhalten von t.Fatal innerhalb eines t.Run?

  1. Reference:
  2. testing package in Go, the relevant excerpt from the article:

Fatal is equivalent to Log followed by FailNow. Log formats its arguments using default formatting, analogous to Println, and records the text in the error log. FailNow marks the function as having failed and stops its execution by calling runtime.Goexit (which then runs all deferred calls in the current goroutine). Execution will continue at the next test or benchmark. FailNow must be called from the goroutine running the test or benchmark function, not from other goroutines created during the test. Calling FailNow does not stop those other goroutines. Run runs f as a subtest of t called name. It runs f in a separate goroutine and blocks until f returns or calls t.Parallel to become a parallel test. Run reports whether f succeeded (or at least did not fail before calling t.Parallel). Run may be called simultaneously from multiple goroutines, but all such calls must return before the outer test function for t returns.

Q31. Was macht log.Fatal?

Example of func Fatal in Go (Golang)

Relevant excerpt from the article:

Fatal is equivalent to Print() followed by a call to os.Exit(1).

Q32. Welches ist ein gültiges Go-Zeitformatliteral?

func Time in Go

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"

Q33. Wie sollten Sie einen Fehler (err) protokollieren?

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.

Q34. Welche Dateinamen erkennt der go test Befehl als Testdateien?

  1. Test packages in go command in Go: ‘Go test’ recompiles each package along with any files with names matching the file pattern “*_test.go”.
  2. Add a test in Go

Q35. Was wird die Ausgabe dieses Codes sein?

ch := 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.

Q36. Was wird die Ausgabe dieses Programms sein?

ch := make(chan int)
close(ch)
val := <-ch
fmt.Println(val)
  1. 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.

  2. Go Playground share, output:

0

Program exited.

Q37. Was wird in diesem Code ausgegeben?

var stocks map[string]float64 // stock -> price
price := stocks["MSFT"]
fmt.Printf("%f\n", price)

Go Playground share, output:

0.000000

Program exited.

Q38. Was ist die gängige Methode, mehrere ausführbare Dateien in Ihrem Projekt zu haben?

  1. stackoverflow
  2. medium
  3. medium

Q39. Wie können Sie main.go in eine ausführbare Datei kompilieren, die auf OSX arm64 läuft?

documentation

Q40. Was ist die korrekte Syntax, um eine Goroutine zu starten, die Hello Gopher! ausgeben wird?

Example of start a goroutine

Q41. Wenn Sie über eine Map in einer for-range-Schleife iterieren, in welcher Reihenfolge werden die Schlüssel:Wert-Paare abgerufen?

Reference

Q42. Was ist eine idiomatische Möglichkeit, die Darstellung einer benutzerdefinierten Struktur in einer formatierten Zeichenkette anzupassen?

Reference

Q43. Wie können Sie ein Goroutine-Leck in diesem Code vermeiden?

func 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")
    }
}

Reference

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.

44. Was wird dieser Code ausgeben?

var i int8 = 120
i += 10
fmt.Println(i)

Go Playground example, output:

-126

Program exited.

45. Angenommen, die Definition von worker lautet wie folgt, was ist die richtige Syntax, um eine Goroutine zu starten, die worker aufruft und das Ergebnis an einen Channel namens ch sendet?

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)

Go Playground example

Q46. Welche Namen sind in diesem Code exportiert?

package os

type FilePermission int
type userID int

Reference 1 Reference 2

Q47. Welches der Folgenden ist korrekt über Strukturen in Go?

Q48. Was macht der eingebaute generate Befehl des Go-Compilers?

Generate Go files by processing source

Q49. Wie können Sie mit dem time-Paket die Zeit 90 Minuten ab jetzt erhalten?

func (Time) Add example

Q50. Ein Programm verwendet einen Channel, um fünf Ganzzahlen in einer Goroutine auszugeben, während der Channel mit Ganzzahlen aus der Hauptroutine gefüttert wird, aber es funktioniert nicht wie es ist. Was müssen Sie ändern, damit es funktioniert?

Reference

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.

Q51. Wie greifen Sie nach dem Import von encoding/json auf die Marshal Funktion zu?

encoding/json#Marshal example

Q52. Was sind die beiden fehlenden Codeteile, die die Verwendung von context.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)
  1. context#WithTimeout
  2. net/http#Request.WithContext

Q53. Wenn Sie eine Struktur namens Client in derselben .go-Datei wie die Anweisung definiert haben, wie exportieren Sie eine Variable mit einem Standardwert, damit die Variable von anderen Paketen zugänglich ist?

Q54. Dieses Programm gibt {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)
}
  1. fmt#Stringer

Q55. Wie würden Sie eine funktionierende 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})
}

Q55. Wie würden Sie eine funktionierende 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})
}

Q56. Wie würden Sie sich von einem durch eine aufgerufene Funktion ausgelösten 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?

Q57. Was wird dieser Code ausgeben?

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 n ist der Zero Value 0.

Q58. Welchen Verb sollten Sie für einen formatierten String verwenden, um die Methode String() string eines benutzerdefinierten Typs aufzurufen?

In Go wird der Verb %s verwendet, um einen String zu formatieren. Bei einem benutzerdefinierten Typ mit definierter String()-Methode wird diese automatisch aufgerufen, und ihr Rückgabewert wird im formatierten String verwendet.

Q59. Welcher Wert ist kein gültiges Layout beim Aufruf von time.Now().Format(layout)?

time#Time.Format

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

Q60. Wie signalisieren Sie dem Go-Compiler, dass die Struktur 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 Typ JSONConverter und weist ihr den Wert (*Namespace)(nil) zu. Dadurch wird sichergestellt, dass Namespace das Interface JSONConverter erfüllt, indem überprüft wird, dass es einer Variablen vom Typ JSONConverter zugewiesen werden kann.

Q61. Welche Aussage über Typisierung und Interfaces ist falsch?

  1. ein Interface.

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.

Q62. Wie würden Sie dieses Programm vervollständigen, um die angegebene Ausgabe zu erzeugen, vorausgesetzt, die SQL-Tabelle ist gegeben?

===[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

Q63. Füllen Sie die Lücken aus

  1. Testdateien in Go müssen _.
  2. Einzelne Tests werden identifiziert durch _.
  3. Sie können Subtests ausführen, indem Sie __.
  4. Sie protokollieren den Fehler und markieren den Test als fehlgeschlagen, indem Sie _.

Q64. Für welchen Typ ist ein rune ein Alias?

  1. Strings, Bytes, Runes und Zeichen in Go

Relevanter Auszug aus dem Artikel:

Der Begriff rune ist in Go ein Alias für den Typ int32, damit Programme klar machen können, wenn ein ganzzahliger Wert einen Code Point darstellt.

Q65. Wann können Sie die Syntax := verwenden, um mehreren Variablen zuzuweisen? Zum Beispiel:

x, err := myFunc()
  1. Short variable declarations

Q66. Wie können Sie die Profiler-Ausgabe in cpu.pprof im Browser ansehen?

Q67. Wann ergibt eine Variable vom Typ interface{} den Wert nil?

Q68. Welchen Wert hält eine String-Variable, wenn sie alloziert, aber nicht zugewiesen wurde?

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.

Q69. Welche eingebaute Funktion wird verwendet, um ein Programm am Weiterlaufen zu hindern?

Die eingebaute Funktion zum Anhalten des Programms ist panic(). Ein Aufruf von panic() löst eine Panic aus und beendet den normalen Ausführungsfluss. Wenn sie nicht abgefangen wird, beendet das Programm.

Q70. Was wird die Ausgabe sein?

a,b := 1, 2
b,c:= 3, 4
fmt.Println(a, b, c)

Go Playground Example

Q71. Was ist der Operator für eine logische UND-Bedingung?

Q72. Was ist eine anonyme Funktion in Go?

Q73. Welches Schlüsselwort wird verwendet, um eine anonyme Funktion in Go zu deklarieren?

Q74. Was ist der Hauptvorteil der Verwendung anonymer Funktionen in Go?

Erläuterung: Sie können inline dort definiert werden, wo sie verwendet werden, was mehr Flexibilität in der Codeorganisation bietet.

Q75. Wie ist die Syntax, um eine anonyme Funktion unmittelbar nach ihrer Deklaration in Go aufzurufen?

reference

Q76. Für welche Typen können Go-Entwickler Methoden definieren?

Methoden 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, string etc. können jedoch keine Methoden direkt angefügt werden. reference