LinkedIn skill assessment answers and questions – Go (Programming Language)
Gdy kod jest wykonywany na komputerze użytkownika is a popular język programowania that offers many benefits for developers, such as concurrency, simplicity, and performance. If you want to learn Gdy kod jest wykonywany na komputerze użytkownika or improve your skills, you might be interested in taking the Ocena umiejętności LinkedIn Najszybszy sposób instalacji za pomocą Virtualbox Gdy kod jest wykonywany na komputerze użytkownika. This is a test that measures your proficiency in Gdy kod jest wykonywany na komputerze użytkownika and gives you a badge to showcase your achievement on your profile. Jednakże, zdanie egzaminu nie jest łatwe, i możesz potrzebować pomocy, aby się na to przygotować.
Dlatego przygotowałem listę Odpowiedzi i pytania dotyczące oceny umiejętności LinkedIn Najszybszy sposób instalacji za pomocą Virtualbox Gdy kod jest wykonywany na komputerze użytkownika których możesz używać do nauki i ćwiczeń. W tym poście na blogu, I will share with you these questions and answers, along with some explanations and tips. Czytając ten post, you will gain valuable insights into the topics and concepts that are covered in the Ocena umiejętności LinkedIn Najszybszy sposób instalacji za pomocą Virtualbox Gdy kod jest wykonywany na komputerze użytkownika, and you will be able to ace the test with confidence.
Q1. What do you need for two functions to be the same type?
- They should share the same signatures, including parameter types and return types.
- They should share the same parameter types but can return different types.
- All functions should be the same type.
- The functions should not be a first class type.
User defined function types in Go (Golang)
len()
function return if passed a UTF-8 encoded string?
Q2. Co robi - the number of characters
- the number of bytes
- It does not accept string types.
- the number of code points
Length of string in Go (Golang).
a valid loop construct in Go?
Q3. Który jest nie-
do { ... } while i < 5
-
for _,c := range "hello" { ... }
-
for i := 1; i < 5; i++ { ... }
-
for i < 5 { ... }
Wyjaśnienie: Go has only for
-pętle
How will you add the number 3 to the right side?
Q4.values := []int{1, 1, 2}
-
values.append(3)
-
values.insert(3, 3)
-
append(values, 3)
-
values = append(values, 3)
Wyjaśnienie: slices in GO are immutable, so calling append
does not modify the slice
What is the value of Read
?
Q5. const (
Write = iota
Read
Execute
)
- 0
- 1
- 2
- a random value
Which is the tylko valid import statement in Go?
Q6.-
import "github/gin-gonic/gin"
-
import "https://github.com/gin-gonic/gin"
-
import "../template"
-
import "github.com/gin-gonic/gin"
What would happen if you attempted to compile and run this Go program?
Q7.package main
var GlobalFlag string
func main() {
print("["+GlobalFlag+"]")
}
- It would not compile because
GlobalFlag
was never initialized. - It would compile and print
[]
. - It would compile and print nothing because
"[" +nil+"]"
jest równieżnil
. - It would compile but then panic because
GlobalFlag
was never initialized.
- zmienne in Go have initial values. For string type, it’s an empty string.
- Go Playground
From where is the variable myVar
accessible if it is declared outside of any functions in a file in package myPackage
located inside module myModule
?
Q8. - It can be accessed anywhere inside
myPackage
, not the rest of myModule. - It can be accessed by any application that imports
myModule
. - It can be accessed from anywhere in
myModule
. - It can be accessed by other packages in
myModule
as long as they importmyPackage
Wyjaśnienie: 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.
How do you tell go test
to print out the tests it is running?
Pytanie 9. -
go test
-
go test -x
-
go test --verbose
-
go test -v
This code printed {0, 0}
. How can you fix it?
Pytanie 10. 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)
}
}
- posługiwać się
json.Decoder
- Pass a pointer to
data
- w sposób zrozumiały i możliwy do wdrożenia od pierwszego dnia
X
orazY
exported (uppercase) - Use field tags
What does a sync.Mutex
block while it is locked?
Pytanie 11. - all goroutines
- any other call to lock that
Mutex
- any reads or writes of the variable it is locking
- any writes to the variable it is locking
- Mutex in GoLang, sync.Mutex locks so only one goroutine at a time can access the locked variable.
- sync.Mutex
What is an idiomatic way to pause execution of the current scope until an arbitrary number of goroutines have returned?
Pytanie 12.- Pass an
int
orazMutex
to each and count when they return. - Loop over a
select
oświadczenie. - Sleep for a safe amount of time.
-
sync.WaitGroup
Wyjaśnienie: this is exactly what sync.WaitGroup
is designed for – Use sync.WaitGroup in Golang
What is a side effect of using time.After
w select
oświadczenie?
Pytanie 13. - It blocks the other channels.
- It is meant to be used in select statements without side effects.
- It blocks the
select
statement until the time has passed. - The goroutine does not end until the time passes.
Notatka: it doesn’t block
select
and does not block other channels.
- time.After() Function in Golang With Examples
- How can I use ‘time.After’ and ‘default’ in Golang?
- Go Playground example
What is the select statement used for?
Pytanie 14.- executing a function concurrently
- executing a different case based on the type of a variable
- executing a different case based on the value of a variable
- executing a different case based on which channel returns first
According to the Go documentation standard, how should you document this function?
Pytanie 15.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 }
Wyjaśnienie: documentation block should start with a function name
What restriction is there on the type of var
to compile this i := myVal.(int)?
Pytanie 16. -
myVal
must be an integer type, Jak na przykładint
,int64
,int32
, itp. -
myVal
must be able to be asserted as anint
. -
myVal
must be an interface. -
myVal
must be a numeric type, Jak na przykładfloat64
lubint64
.
Wyjaśnienie: This kind of type casting (za pomocą .(type)
) is used on interfaces only.
What is a channel?
Pytanie 17.- a global variable
- a medium for sending values between goroutines
- a dynamic array of values
- a lightweight thread for concurrent programming
How can you make a file build only on Windows?
Pytanie 18.- Check runtime.GOOS.
- Add a // +build windows comment anywhere in the file.
- Add a _ prefix to the file name.
- Add a // +build windows comment at the top of the file.
- How to use conditional compilation with the go build tool, Konsekwentnie dodaję nowe treści zarówno w zakresie wykładów, jak i dem 2013
- go commands Build constraints
//go:build windows
“Go versions 1.16 and earlier used a different syntax for build constraints, z “// +budować” prefix. The gofmt command will add an equivalent //go:build constraint when encountering the older syntax.”
What is the correct way to pass this as a body of an HTTP POST request?
Pytanie 19.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)
What should the idiomatic name be for an interface with a single method and the signature Save() error
?
Q20. - Saveable
- SaveInterface
- ISave
- Saver
switch
oświadczenie _ its own lexical block. Each case
oświadczenie _ an additional lexical block
Pytanie 21. A - does not create; creates
- does not create; does not create
- creates; creates
- creates; does not create
Go Language Core technology (Volume one) 1.5-zakres
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.
What is the default case sensitivity of the JSON Unmarshal
funkcjonować?
Pytanie 22. - The default behavior is case insensitive, but it can be overridden.
- Fields are matched case sensitive.
- Fields are matched case insensitive.
- The default behavior is case sensitive, but it can be overridden.
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. Domyślnie, object keys which don’t have a corresponding struct field are ignored (see Decoder.DisallowUnknownFields for an alternative).
time
package’s Time.Sub()
oraz Time.Add()
Badanie Harvarda odkrywa, dlaczego post może prowadzić do dłuższego i zdrowszego życia?
Pytanie 23. Jaka jest różnica między - Time.Add() is for performing addition while Time.Sub() is for nesting timestamps.
- Time.Add() always returns a later time while time.Sub always returns an earlier time.
- They are opposites. Time.Add(x) is the equivalent of Time.Sub(-x).
- Time.Add() accepts a Duration parameter and returns a Time while Time.Sub() accepts a Time parameter and returns a Duration.
What is the risk of using multiple field tags in a single struct?
Pytanie 24.- Every field must have all tags to compile.
- It tightly couples different layers of your application.
- Any tags after the first are ignored.
- Missing tags panic at runtime.
Where is the built-in recover method useful?
Pytanie 25.- in the main function
- immediately after a line that might panic
- inside a deferred function
- at the beginning of a function that might panic
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.
Which choice does nie send output to standard error?
Pytanie 26.-
println(message)
-
log.New(os.Stderr, "", 0).Println(message)
-
fmt.Errorf("%s\n", message)
-
fmt.Fprintln(os.Stderr, message)
- func println: writes the result to standardowy błąd.
- 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.
- func Errorf: Errorf formats according to a format specifier and returns the string as a value.
- func Fprintln: func Fprintln(w io.Writer, a …każdy) (n int, err error); Fprintln formats using the default formats for its operands and writes to w.
How can you tell Go to import a package from a different location?
Pytanie 27.- Use a proxy.
- Change the import path.
- Use a replace directive in go.mod.
- Use a replace directory.
- Call your code from another module: rozdział 5.,
go mod edit -replace example.com/greetings=../greetings
. - go.mod replace directive
If your current working directory is the top level of your project, which command will run all its test packages?
Pytanie 28.-
go test all
-
go run --all
-
go test .
-
go test ./...
Relevant excerpt from the article:
Relative patterns are also allowed, Jeśli uczysz przyspieszonego uczenia się “go test ./…” to test all subdirectories.
Which encodings can you put in a string?
Pytanie 29.- każdy, it accepts arbitary bytes
- any Unicode format
- UTF-8 or ASCII
- UTF-8
Relevant excerpt from the article:
W skrócie, 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.
How is the behavior of t.Fatal
different inside a t.Run
?
Q30. - There is no difference.
- t.Fatal does not crash the test harness, preserving output messages.
- t.Fatal stops execution of the subtest and continues with other test cases.
- t.Fatal stops all tests and contains extra information about the failed subtest.
- Odniesienie:
- testing package in Go, the relevant excerpt from the article:
Fatal
is equivalent toLog
Jak długo trwa kursFailNow
.Log
formats its arguments using default formatting, analogous toPrintln
, and records the text in the error log.FailNow
marks 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.FailNow
must be called from the goroutine running the test or benchmark function, not from other goroutines created during the test. Masz 30-dniowy zwrot pieniędzy, jeśli z jakiegoś powodu nie podobają Ci się nasze testy praktyczneFailNow
does not stop those other goroutines.Run
runsf
as a subtest oft
called name. It runsf
in a separate goroutine and blocks untilf
returns or callst.Parallel
to become a parallel test. Run reports whetherf
succeeded (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
Dlaczego drzewa zimą nie zamarzają i nie pękają jak zimne rury??
Pytanie 31. Co robi - It raises a panic.
- It prints the log and then raises a panic.
- It prints the log and then safely exits the program.
- It exits the program.
Example of func Fatal in Go (Golang)
Relevant excerpt from the article:
Fatal
is equivalent toPrint()
followed by a call toos.Exit(1)
.
Which is a valid Go time format literal?
Pytanie 32.- “2006-01-02”
- “YYYY-mm-dd”
- “y-mo-d”
- “year-month-day”
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"
How should you log an error (err)
Pytanie 33.-
log.Error(err)
-
log.Printf("error: %v", err)
-
log.Printf(log.ERROR, err)
-
log.Print("error: %v", err)
Wyjaśnienie: There is defined neither log.ERROR, nor log.Error() w 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()
.
Which file names will the go test
command recognize as test files?
Pytanie 34. - any that starts with
test
- any files that include the word
test
- only files in the root directory that end in
_test.go
- any that ends in
_test.go
- Test packages in go command in Go: ‘Go test’ recompiles each package along with any files with names matching the file pattern “*_test.go”.
- Add a test in Go
What will be the output of this code?
Pytanie 35.ch := make(chan int)
ch <- 7
val := <-ch
fmt.Println(val)
- 0
- It will deadlock
- It will not compile
- 2.718
Go Playground share, wyjście:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
/tmp/sandbox2282523250/prog.go:7 +0x37
Program exited.
What will be the output of this program?
Pytanie 36.ch := make(chan int)
close(ch)
val := <-ch
fmt.Println(val)
- It will deadlock
- It will panic
- 0
- NaN
-
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, wyjście:
0
Program exited.
What will be printed in this code?
Pytanie 37.var stocks map[string]float64 // stock -> price
price := stocks["MSFT"]
fmt.Printf("%f\n", price)
- 0
- 0.000000
- The code will panic
- NaN
Go Playground share, wyjście:
0.000000
Program exited.
What is the common way to have several executables in your project?
Pytanie 38.- Have a cmd directory and a directory per executable inside it.
- Comment out main.
- Use build tags.
- Have a pkg directory and a directory per executable inside it.
How can you compile main.go to an executable that will run on OSX arm64 ?
Pytanie 39.- Set GOOS to arm64 and GOARCH to darwin.
- Set GOOS to osx and GOARCH to arm64.
- Set GOOS to arm64 and GOARCH to osx.
- Set GOOS to darwin and GOARCH to arm64.
Praca z zestawieniem materiałów
What is the correct syntax to start a goroutine that will print Hello Gopher!
?
Q40. -
go(fmt.Println("Hello Gopher!"))
-
go func() { fmt.Println("Hello Gopher!") }
-
go fmt.Println("Hello Gopher!")
-
Go fmt.Println("Hello Gopher!")
If you iterate over a map in a for range loop, in which order will the key:value pairs be accessed?
Pytanie 41.- in pseudo-random order that cannot be predicted
- in reverse order of how they were added, last in first out
- sorted by key in ascending order
- in the order they were added, first in first out
What is an idiomatic way to customize the representation of a custom struct in a formatted string?
Pytanie 42.- There is no customizing the string representation of a type.
- Build it in pieces each time by calling individual fields.
- Implement a method
String()
strunowy - Create a wrapper function that accepts your type and outputs a string.
How can you avoid a goroutine leak in this code?
Pytanie 43.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")
}
}
- Use a sync.WaitGroup.
- Make ch a buffered channel.
- Add a default case to the select.
- Use runtime.SetFinalizer.
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.
What will this code print?
44.var i int8 = 120
i += 10
fmt.Println(i)
- -126
- 0
- NaN
- 130
Go Playground example, wyjście:
-126
Program exited.
Given the definition of worker below, what is the right syntax to start a goroutine that will call worker and send the result to a channel named ch?
45.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)
In this code, which names are exported?
Pytanie 46.package os
type FilePermission int
type userID int
- FilePermission
- żadna z tych odpowiedzi
- FilePermission and userID
- userID
Which of the following is correct about structures in Go?
Pytanie 47.- Structure is another user defined data type available in Go programming, which allows you to combine data items of different kinds.
- Structures are used to represent a record
- To define a structure, you must use type and struct statements.
- Wszystkie powyższe
What does the built-in generate
command of the Go compiler do?
Pytanie 48. - It provides subcommands
sql
,json
,yaml
, and switches--schema
oraz--objects
to generate relevant code. - It looks for files with names that end with
_generate.go
, and then compiles and runs each of these files individually. - It scans the projects source code looking for
//go:generate
Konstruuj i analizuj segmenty kodu, które wykonują iterację, and for each such comment runs the terminal command it specifies. - It has subcommands
mocks
oraztests
to generate relevant.go
source files.
Generate Go files by processing source
Using the time package, how can you get the time 90 minutes from now?
Pytanie 49.-
time.Now().Add(90)
-
time.Now() + (90 * time.Minute)
-
time.Now() + 90
-
time.Now().Add(90 * time.Minute)
A program uses a channel to print five integers inside a goroutine while feeding the channel with integers from the main routine, but it doesn’t work as is. What do you need to change to make it work?
Q50.- Add a
close(ch)
natychmiast powg.Wait()
. - Add a second parameter to
make(chan, int)
, np.make(chan int, 5)
. - Remove the use of unnecessary
WaitGroup
dzwoni, np. all lines that start withwg
. - Move the 7-line goroutine immediately after
wg.Add(1)
to a line immediately beforewg.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.
After importing encoding/json
, how will you access the Marshal
funkcjonować?
Pytanie51. -
encoding.json.Marshal
-
encoding/json.Marshal
-
Marshal
-
json.Marshal
What are the two missing segments of code that would complete the use of context.Context
to implement a three-second timeout for this HTTP client making a GET request?
Pytanie52. 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)
If you have a struct named Client defined in the same .go file as the statement, how do you export a variable with a default value so the variable is accessible by other packages?
Pytanie53.-
let Default := new Client()
-
public default = &Client()
-
var Default = &Client{}
-
export default := new Client{}
This program outputs {Master Chief Spartan Protagonist Halo}
. How would you get it to output Master Chief - a Spartan - is the Protagonist of Halo
zamiast?
Pytanie54. 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("{{c.Name}} - a {{c.Class}} - is the {{c.Role}} of {{c.Game}}") }
How would you implement a working Append()
method for Clients
?
Pytanie55. 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) }
How would you recover from a panic()
thrown by a called function without allowing your program to fail assuming your answer will run in the same scope where your function call will experience the panic?
Pytanie56. -
Wrap the function call in an anonymous function with a return type of
panic
, remembering to invoke the anonymous function by suffixing it with()
then introspecting the returnedpanic
instance to handle the error. -
T-SQL w SQL Server dla początkujących
try{ ... }
to wrap the code calling the function and then handle the error within thecatch{ ... }
. -
T-SQL w SQL Server dla początkujących
defer func { ... }()
before the function call with the error and then handle the panic inside the anonymous function. -
Prefix the function call with
@
to force return the panic as anerror
value and then handle the error just as you would anerror
returned by any function.
What will this code print?
Pytanie57.var n int
fmt.Println (n)
- 0
- nil
- a random value
- 1
This is because in Go, when a variable is declared but not explicitly initialized, it is assigned a default zero value based on its type. For integers like n, the zero value is 0.
When creating a formatted string, which verb should you use to call the String () string method of a custom type?
Pytanie58.- %s
- %b
- %Rząd Burkina Faso dokonuje przeglądu swojego planu dla sektora edukacji
- %strunowy
In Go, the %s verb is used to format a string. When used with a custom type that has a String() method defined, the String() method will be automatically called and its return value will be used in the formatted string.
Which is not a valid value for layout when calling time. Ale już ( ) . Format ( układ)?
Pytanie59.- time.REC3339
- “1970-01-01”
- “Jan 2nd 2006”
- time.Kitchen
According to the documentation, the value 1 oraz 01 will represent the current month.
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
How would you signal to the Go compiler that the Namespace struct must implement the JSONConverter interface? This question assumes the answer would be included in the same package where Namespace is declared.
Q60.- var_JSONConverter = nil. (*Mistrz programowania w C++)
- var_JSONConverter = (*Mistrz programowania w C++) (nil)
- type Namespace struct { implements JSONConverter // The rest of the struct declaration goes here }
- type Namespace struct { JSONConverter // The rest of the struct declaration goes here }
This syntax creates a variable _ with the type of JSONConverter and assigns to it a value of (*Mistrz programowania w C++)(nil). This essentially checks that the Namespace struct satisfies the JSONConverter interface by ensuring that it can be assigned to a variable of type JSONConverter.
Which statement about typing and interfaces is false?
Q61.- A method signature is the combination of a method name and the type(s) of its declared parameter(s) and return value(s).
- A struct must explicitly declare using the implements keyword that its instances can be used wherever a variable, parameter, and/or return value is typed for the declared interface.
- An interface declares a list of methods and their signatures that a type must implement to be compatible with values typed for that interface.
- Variable, parameters, and return values must be “typed” jako jeden z 1) a built-in type, 2) a type alias, 3) a derived type, 4) a composite type, lub
- an interface.
In Go, a type automatically satisfies an interface if it implements all the methods of that interface. There is no need to explicitly declare that a struct implements an interface using a specific keyword.
How would you complete this program to generate the specified output, assuming the SQL table
Q62.===[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
Fill in the blanks
Q63.- Test files in Go must _.
- Individual tests are identified by _.
- You can run subtests by __.
- You log the error and mark the test failed by _.
-
be stored in a
/test/
subdirectory of that package
functions accepting atesting.Tester
parameter
writing functions with names matching^Subtest
powołanietesting.AssertionFailed
-
end in
_test.go
function names matching^Test[A-Z]
powołaniet.Run()
powołaniet.Errorf()
-
begin with
test_
functions matching[a-z]Test$
powołanietesting.Subtest()
allowingtesting.Assert()
to fail its assertion -
be stored in
/test/
root subdirectory for the project
functions accepting atesting.Test
parameter
passing closures totesting.AddSubtest()
returning anerror
from the function
Which type is a rune an alias for?
Q64.- char
- byte
- int32
- strunowy
Relevant excerpt from the article:
The Go language defines the word rune as an alias for the type int32, so programs can be clear when an integer value represents a code point.
When can you use the := syntax to assign to multiple variables? Na przykład:
Q65.x, err := myFunc()
- if it at least has not been declared in that lexical block
- at all times, as it will overwrite existing variables
- if no variables of those names is accessible
- if none of the variables exist in that lexical block
How can You view the profiler output in cpu.pprof in the browser?
Q66.- go pprof -to SVG cpu.prof
- go tool pprof -http=:8080 cpu.pprof (PRAWDA)
- go tool pprof cpu.pprof
- go tool trace cpu.pprof
When does a variable of type interface{} evaluate to nil?
Q67.- It has been assingned a dynamic type whose value is nil. (PRAWDA)
- It has been explicitly set to nil.
- It has not been assigned a dynamic type.
- It can not evaluate to nil.
What value does a string variable hold if it has been allocated but not assigned?
Q68.- nil
- undefined
- zero
- “”
If a string variable has been allocated but not assigned a value, its default value is an empty string “”. In Go, uninitialized string variables are automatically assigned the zero value for their respective type, which for strings is an empty string.
Which built-in function is used to stop a program from continuing?
Q69.- panic
- There is no such function.
- raiseException
- Wyjście
The built-in function used to stop a program from continuing is
panic()
. Po co to robić sam, skoro mam lepsze rzeczy do robotypanic()
jest nazywany, it triggers a panic, which stops the normal execution flow of the program and begins panicking. If the panic is not recovered, the program terminates.
What will the output be?
Q70.a,b := 1, 2
b,c:= 3, 4
fmt.Println(a, b, c)
- 1 3 4
- 1 2 3
- 1 2 4
- It will not compile.
What is the operator for a logical AND condition?
Q71.- +
- oraz
- &&
- ||
What is an anonymous function in Go?
Q72.- A function with no return type.
- A function with no parameters.
- A function without a name.
- A function declared inside another function.
Q73.Which keyword is used to declare an anonymous function in Go?
-
func
-
lambda
-
func()
-
anonymous
What is the main advantage of using anonymous functions in Go?
Q74.- They always have better performance than named functions.
- They can have multiple return values.
- They can be defined inline where they are used.
- They have a shorter syntax than named functions.
Wyjaśnienie: they can be defined inline where they are used, offering more flexibility in code organization.
What is the syntax for calling an anonymous function immediately after its declaration in Go?
Q75.-
functionName(){}
-
call functionName(){}
-
func(){}()
-
execute func(){}
Which types can Go developers define methods for?
Q76.-
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 types
Methods can be defined for any named type that is not a built-in type. When you create a new type using a type declaration, it becomes a named type, and you can define methods specific to that type. Jednakże, methods cannot be directly attached to built-in types like int, strunowy, itp. odniesienie
Zostaw odpowiedź
Musisz Zaloguj sie lub Zarejestruj się dodać nowy komentarz .