“14” stage from the uncle’s 80 small targets and 66, share something special today, uncle today to dry is the foundation of Golang questions compiled by these high frequency is also interview subject, in addition, the basic question may continue after the series of uncle output share with everyone, mutombo think it strongly, it is necessary to the uncle is organizing the first edition, Come and lay the foundation with uncle!
Golang basic questions
1. What is the output of this code?
func main(a) {
defer func(a) { fmt.Println("Before printing") }()
defer func(a) { fmt.Println("Printing") }()
defer func(a) { fmt.Println("After printing") }()
panic("Trigger exception")}Copy the code
Output: After printing before printing Panic: an exception is triggered……
When the coroutine encounters panic, it iterates through the defer list of the coroutine (defer is a linked list structure, and the new defer is appended to the top of the defer list, which can be understood as last in, first out) and executes defer. During the process of defer, panic will be stopped if recover is encountered, and we will return to recover and continue to execute. If RECOVER is not encountered, the panic message is thrown to stderr after iterated through the defer linked list of the coroutine
2. What does the following code output?
func calc(index string, a, b int) int {
ret := a + b
fmt.Println(index, a, b, ret)
return ret
}
func main(a) {
a := 1
b := 2
defer calc("1", a, calc("10", a, b))
a = 0
defer calc("2", a, calc("20", a, b))
b = 1
}
Copy the code
Output: 10 1 2 3 20 0 2 2 2 20 2 2 1 1 3 4
Parsing: Note here that when the defer definition is executed, the parameters are first evaluated and then pushed onto the function call stack. The body of the defer function is not called at this point, but only when the function returns. When an argument is pushed onto the function call stack, the value is copied if the argument is of a value type, and if the argument is a pointer, the pointer is copied instead of the value to which the pointer points.
3. What does the following code output?
func main(a) {
slice := []int{0.1.2.3}
m := make(map[int] *int)
for key, val := range slice {
m[key] = &val
}
for k, v := range m {
fmt.Printf("key: %d, value: %d \n", k, *v)
}
}
Copy the code
Key: 0, value: 3 Key: 1, value: 3 Key: 2, value: 3 Key: 3, value: 3
Val is the same global variable throughout the loop, and the address is the same. Each time the address is overwritten by the new value, so at the end of the loop, the address is the last element in the slice, 3. Golang’s ego is looped into a for-range loop
4. What does the following code output
func main(a) {
i := make([]int.5)
i = append(i, 1.2.3)
fmt.Println(i)
j := make([]int.0)
j = append(j, 1.2.3.4)
fmt.Println(j)
}
Copy the code
[0 0 0 0 1 2 3] [1 2 3 4]
When the make function creates a slice, it allocates an array of the specified length, initializes to 0, and returns a slice referencing the array
5. Is there an error in the following code?
func funcMui(x,y int)(sum int,error){
return x+y,nil
}
Copy the code
The second return value is not named. If a function has more than one return value, the others must also be named. If more than one value is returned, parentheses () must be added; If there is only one return value, the name must also be parentheses (). Here, the first return value has the name “sum”, and the second return value is not named, so it is an error.
6. Difference between new() and make()
The difference between new and make
- New returns a pointer to the Type, Type *Type; Make returns the reference type itself;
- The space allocated by new is cleared to zero, which is the zero value of the type (zero for int, “” for string, nil for reference). Make allocates space and initializes it.
- New allocates data of any type. Make allocates and initializes only slice, Map, and chan data
7. Does the following code compile? If so, what is the output?
func main(a) {
list := new([]int)
list = append(list, 1)
fmt.Println(list)
s1 := []int{1.2.3}
s2 := []int{4.5}
s1 = append(s1, s2)
fmt.Println(s1)
}
Copy the code
> Parse: compilation error
List after new([]int) is a pointer to *[]int. S1 = append(s1, s2…); s1 = append(s1, s2…);
8. Can the following code be compiled
func Test7(t *testing.T) {
sn1 := struct {
age int
name string
}{age: 11, name: "qq"}
sn2 := struct {
age int
name string
}{age: 11, name: "qq"}
// Can be compared
if sn1 == sn2 {
fmt.Println("sn1 == sn2")
}
sm1 := struct {
age int
m map[string]string
}{age: 11, m: map[string]string{"a": "1"}}
sm2 := struct {
age int
m map[string]string
}{age: 11, m: map[string]string{"a": "1"}}
// Compile error, map cannot be compared
if sm1 == sm2 {
fmt.Println("sm1 == sm2")}}Copy the code
Golang struct can not be compared
9. How can I access the member variable name through the pointer variable p?
A. p.name
B. (&p).name
C. (*p).name
D. p->name
Copy the code
Answer: AC
10. What is syntactically correct about string concatenation
A. str := 'abc' + '123'
B. str := "abc" + "123"
C. str := '123' + "abc"
D. fmt.Sprintf("abc%d".123)
Copy the code
Answer: the BD
11. What does the following code output about IOTA?
func main(a) {
const (
x = iota
_
i
j
y
z = "aa"
o
k = iota
p
q
)
fmt.Println(x,i,j, y, z,o, k, p, q)
}
Copy the code
Output: 0 2 3 4 AA AA 7 8 9
The value of the following constant is the same as the value of the current constant. The value of the following constant is the same as the value of the current constant. During this process, ioTA keeps the state of autoincrement
12. The following assignment is correct
A. var x = nil
B. var x interface{} = nil
C. var x string = nil
D. var x error = nil
Copy the code
Answer: the BD
13. Which of the following is grammatically correct about channel?
A. var ch chan int
B. ch := make(chan int)
C. <- ch
D. ch <-
Copy the code
Answer: ABC
When writing data to a channel, the <- end must have a value
14. What does the following code output?
func hello (num ...int) {
num[0] = 18
}
func main(a) {
i := []int{5.6.7}
hello(i...)
fmt.Println(i[0])
}
A18.
B. 5
C.Compilation error
Copy the code
Answer: 18
Func hello (num… Int) is an expression that passes in a variable argument to a function. . []type is a pointer to an array. []type is a pointer to an array. []type is a pointer to an array.
15. Which of the following?
func main(a) {
a := 5
b := 8.1
fmt.Println(a + b)
}
A13.1.
B13.
C.compilation error
Copy the code
Answer: C
Integer and floating point cannot be added
16. What does the following code output?
func Test15(t *testing.T) {
a := [5]int{1.2.3.4.5}
s := a[3:4:4]
fmt.Println(s[0])}Copy the code
Answer: 4
A [low: high: Max], where a[low: high] generates slices, and the capacity of slices is equal to (max-low)
17. What does the following code output?
func main(a) {
a := [2]int{5.6}
b := [3]int{5.6}
if a == b {
fmt.Println("equal")}else {
fmt.Println("not equal")
}
}
A. compilation error
B. equal
C. not equal
Copy the code
Answer: A,
A comparison of arrays requires that they have the same length
Which of the following types can use cap()
A. array
B. slice
C. map
D. channel
Copy the code
Answer: ABD
The cap() function only supports array Pointers (*array), slice, and channel.
19. What does the following code output?
func main(a) {
var i interface{}
if i == nil {
fmt.Println("nil")
return
}
fmt.Println("not nil")}Copy the code
Answer: nil
Nil (point, function, interface, slice, channel, map); The zero value of an integer is 0; A floating point number has a zero value of 0.0; String zero is an empty string “”
20. What does the following code output?
func main(a) {
s := make(map[string]int)
delete(s, "h")
fmt.Println(s["h"])}Copy the code
Answer: 0
If the map is nil or the key-value pair does not exist, delete does not do any operation and the program does not report an error. When a nonexistent key-value pair is obtained, the return value is zero of the corresponding type, so 0 is returned
21. What does the following code output?
func main(a) {
i := - 5
j := +5
fmt.Printf("%+d %+d", i, j)
}
Copy the code
Answer: -5 +5
%+d is signed output
Define a global string variable. Which of the following is correct?
A. var str string
B. str := ""
C. str = ""
D. var str = ""
Copy the code
Answer: the AD
B) only local variable declarations are supported. C is the assignment statement, and STR must be declared before that
23. What does the following code output?
func f(i int) {
fmt.Println(i)
}
func main(a) {
i := 5
defer f(i)
i += 10
}
Copy the code
Answer: 5
Parsing: The arguments to the f() function save a copy when the defer statement is executed and are used when the f() function is actually called, so 5
24. What does the following code output?
func main(a) {
str := "hello"
str[0] = 'x'
fmt.Println(str)
}
A. hello
B. xello
C. compilation error
Copy the code
C) compiling error
In Golang, strings are read-only and can be printed, such as fmt.println (STR [0]), and cannot be modified
25. What is the correct function call about mutable arguments?
func add(args ...int) int {
sum := 0
for _, arg := range args {
sum += arg
}
return sum
}
A. add(1.2)
B. add(1.3.7)
C. add([]int{1.2})
D. add([]int{1.3.7}...).Copy the code
Answer: ABD
[]type{}… Format? Don’t ask. Ask is the rule
26, Which variable will print yes nil
func main(a) {
var s1 []int
var s2 = []int{}
if___ = =nil {
fmt.Println("yes nil")}else {
fmt.Println("no nil")}}Copy the code
Answer: s1
Nil slice is equal to nil; S2 represents an empty slice, represents an empty set, and is not equal to nil
27. What does the following code output?
func main(a) {
i := 65
fmt.Println(string(i))
}
A. A
B. 65
C. compilation error
Copy the code
Answer: A,
In UTF-8, the decimal number 65 corresponds to the symbol A
28. What are the capacities of section A, B and C respectively?
func main(a) {
s := [3]int{1.2.3}
a := s[:0]
b := s[:2]
c := s[1:2:cap(s)]
fmt.Println(cap(a))
fmt.Println(cap(b))
fmt.Println(cap(c))
}
Copy the code
Answer: 3, 3, 2
[A :b:c] the size of the array is equal to the length of the data. [A: B :c] The size of the array is equal to the length of the data. [B: C] The size of the array is equal to the length of the data.
29. What does the following code output?
func increaseA(a) int {
var i int
defer func(a) {
i++
}()
return i
}
func increaseB(a) (r int) {
defer func(a) {
r++
}()
return r
}
func main(a) {
fmt.Println(increaseA())
fmt.Println(increaseB())
}
Copy the code
Answer: 0, 1
Have you marked the details of how to use the potholes in defer
What do functions f1(), f2(), f3() return?
func f1(a) (r int) {
defer func(a) {
r++
}()
return 0
}
func f2(a) (r int) {
t := 5
defer func(a) {
t = t + 5} ()return t
}
func f3(a) (r int) {
defer func(r int) {
r = r + 5
}(r)
return 1
}
func main(a) {
fmt.Println(f1())
fmt.Println(f2())
fmt.Println(f3())
}
Copy the code
Answer: 1, 5, 1
Have you marked the details of how to use the potholes in defer
31. What does the following code output?
type Person struct {
age int
}
func main(a) {
person := &Person{28}
defer fmt.Printf("1: %v\n", person.age)
defer func(p *Person) {
fmt.Printf("Output 2: %v\n", p.age)
}(person)
defer func(a) {
fmt.Printf("Output 3: %v\n", person.age)
}()
person.age = 29
}
Copy the code
Answer: Output 3:29 Output 2:29 Output 1:28
Resolution: Output 3 referred to as a closure, so the output and output 2 as a function parameter, equivalent to a variable copy, here is a copy of the pointer variable, the value of the pointer variable is pointing to the address of original variables, thus eventually output and output 1 as a function parameter, defined in the defer when the value passed to defer the function body cache, So the output is 28
Do the following two slice declarations have the above differences? Which is preferable?
A. var a []int
B. a := []int{}
Copy the code
Answer: A,
A declares nil slices; B declares an empty slice whose length and capacity are both 0. The declaration of A does not allocate memory, preferentially
33, A, B, C, D
type S struct{}func m(x interface{}){}func g(x *interface{}){}func main(a) {
s := S{}
p := &s
m(s) //A
g(s) //B
m(p) //C
g(p) //D
}
Copy the code
B, D will edit errors
Resolution: Interface {} can accept any type of argument, including user-defined types, even if it is a pointer type, use interface {} instead of *interface {}. Never use a pointer to an interface type, because it is already a pointer.
34. What does the following code output?
func main(a) {
s1 := []int{1.2.3}
s2 := s1[1:]
s2[1] = 4
fmt.Println(s1)
s2 = append(s2, 5.6.7)
fmt.Println(s1)
}
Copy the code
[1 2 4]
Interviewer: Slice as a function parameter is pass value or pass quote?
What does the following code output?
func main(a) {
if a := 1; false{}else if b := 2; false{}else {
fmt.Println(a, b)
}
}
Copy the code
Answer: 1, 2
Parsing: The if statement declares a variable whose scope belongs only to the entire if block structure
What does the following code output
func calc(index string, a, b int) int {
ret := a + b
fmt.Println(index, a, b, ret)
return ret
}
func main(a) {
a := 1
b := 2
defer calc("A", a, calc("10", a, b))
a = 0
defer calc("B", a, calc("20", a, b))
b = 1
}
Copy the code
Answer: 10 20 0 1 2 3 2 2 B 0 1, 3, 4, 2, 2 A
Have you marked the details of how to use the potholes in defer
What does the following code output
func main(a) {
m := map[int]string{0: "zero".1: "one"}
for k, v := range m {
fmt.Println(k, v)
}
}
Copy the code
1 one 0 zero or 0 zero 1 one
The map output is unordered
38. Can the following code be printed normally
type People interface {
Speak(string)}type Student struct{}
func (stu *Student) Speak(think string) {
fmt.Println(think)
}
func main(a) {
var peo People
student := Student{}
peo = student
peo.Speak("speak")}Copy the code
Student does not implement People (Speak method has pointer receiver)
*Student implements the Speak interface, not the Student type. If Student implements the Speak method, then Student{} or &student {} can access the method.
39. What does the following code output
const (
a = iota
b = iota
)
const (
name = "name"
c = iota
d = iota
)
func main(a) {
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println(d)
}
Copy the code
Answer: 0, 1, 1, 2
Resolution: 1. Each const block resets and initializes the IOTA to 0. Each new line of the const block that declares the IOTA increases by 1. Iota is also initialized on the first line (with a value of 0), after which the constant increments by 1
40. What does the following code output?
func main(a) {
const a = iota
const b = iota + 3
const c, d = iota.iota + 3
const (
e = iota // e=0
f = iota + 4 // f=5
g // g=6
)
println(a, b, c, d, e, f, g)
}
Copy the code
Answer: 0, 3, 0, 3, 5, 6
38
41. What does the following code output?
type People interface {
Show()
}
type Student struct{}
func (stu *Student) Show(a){}func main(a) {
var s *Student
if s == nil {
fmt.Println("s is nil")}else {
fmt.Println("s is not nil")}var p People = s
if p == nil {
fmt.Println("p is nil")}else {
fmt.Println("p is not nil")}}Copy the code
S is nil p is not nil
Interface type values are nil if and only if both dynamic values and dynamic types are nil. In the code above, when we assign to p, the dynamic value of p is nil, but the dynamic type is *Student, which is a nil pointer, so the equality condition is not true.
42. What does the following code output
type Direction int
const (
North Direction = iota
East
South
West
)
func (d Direction) String(a) string {
return[...].string{"North"."East"."South"."West"}[d]
}
func main(a) {
fmt.Println(South)
}
Copy the code
Answer: the South
If you override the String method in Go, the String method is automatically executed when fmt.Println is called
43. Can the following code output normally
type Square struct {
x, y int
}
var m = map[string]Square{
"foo": Square{2.3}},func main(a) {
m["foo"].x = 1
fmt.Println(m["foo"].x)
}
Copy the code
Answer: Failed to compile
For assignment operations like X = Y, the address of X must be known before the value of Y can be assigned to X, but the value of the map in Go is itself unaddressable. There are two ways to write it correctly:
square := m["foo"] square.x = 1 Copy the code
M [“foo”] = x;
var m = map[string]*Square{ "foo": &Square{2.3}, } m["foo"].x = 1 Copy the code
This modifies the x variable in m[“foo”]
44. What does the following code output
var p *int
func foo(a) (*int, error) {
var i int = 5
return &i, nil
}
func bar(a) {
//use p
fmt.Println(*p)
}
func main(a) {
p, err := foo()
iferr ! =nil {
fmt.Println(err)
return
}
bar()
fmt.Println(*p)
}
Copy the code
The bar function can cause a panic, null pointer exception
P in err := foo () is the local variable redeclared, not the global variable p we declared earlier
45. What does this code output
func main(a) {
v := []int{1.2.3}
for i := range v {
v = append(v, i)
fmt.Println(v)
}
}
Copy the code
[1 2 3 0 1] [1 2 3 0 1]
Golang’s ego is looped into a for-range loop
46. What does the following code output?
func main(a) {
var m = [...]int{1.2.3}
for i, v := range m {
go func(a) {
fmt.Println(i, v)
}()
}
time.Sleep(time.Second * 1)}Copy the code
Answer: 2 3 2 3 3\
Parse: for range iterates over the variables with a short variable declaration (:=). Note that variables I and v are reused each time in the body of the loop, not redeclared. See article for more details: Golang’s ego is looped into a for-range loop
47. What does the following code output?
func test(n int) (r int) {
// The first defer
defer func(a) {
r += n
recover() ()}var f func(a)
// The second defer
defer f()
f = func(a) {
r += 2
}
return n + 1
}
func main(a) {
fmt.Println(test(3))}Copy the code
First, defer is used with functions whose return values are named, and the defer statement is defined to refer to external variables as closure references (see article for details). Have you marked the details of the use of the bumps and holes in defer? It is suggested that you read the article before moving on, otherwise some students may be a little hard to connect.) Why did the second defer not work? In fact, the second defer function did nothing, even causing panic when f() was executed. We all know that the program does not execute immediately after it reaches the defer definition, but instead builds a linked list of the captured results of defer, pushes the associated functions onto the stack cache, and then executes off the stack before the program returns. The problem is obvious. What is f when the program executes to defer f()? F is nil, so at the end of the stack a nil function is executed, equivalent to:
var f func(a) f() // panic: runtime error: invalid memory address or nil pointer dereference Copy the code
So that’s why the first defer had the recover() method. F = func() {r += 2}; f = func() {r += 2
48. What does the following code output
func test(n int) (r int) {
// The first defer
defer func(a) {
r += n
}()
var f func(a)
f = func(a) {
r += 2
}
// The second defer
defer f()
return n + 1
}
func main(a) {
fmt.Println(test(3))}Copy the code
47
What does the following code output
func main(a) {
var a = [5]int{1.2.3.4.5}
var r [5]int
for i, v := range a {
if i == 0 {
a[1] = 12
a[2] = 13
}
r[i] = v
}
fmt.Println("r = ", r)
fmt.Println("a = ", a)
}
Copy the code
A = [1 12 13 4 5]\
Golang’s ego is looped into a for-range loop
50. What does the following code output?
func main(a) {
slice := make([]int.5.5)
slice[0] = 1
slice[1] = 2
change(slice...)
fmt.Println(slice)
change(slice[0:2]...). fmt.Println(slice) }Copy the code
Answer: [1 2 0 0 0]
Interviewer: Is slice passed as a function parameter by value or by reference?
51. What does the following code output
func main(a) {
var m = map[string]int{
"A": 21."B": 22."C": 23,
}
counter := 0
for k, v := range m {
if counter == 0 {
delete(m, "A")
}
counter++
fmt.Println(k, v)
}
fmt.Println("counter is ", counter)
}
Copy the code
Answer: Counter is 2 or counter is 3 for range map is unordered
52. What is true about coroutines
A. Both coroutines and threads can realize concurrent execution of programs; B. Threads are lighter than coroutines; C. Coroutines do not have deadlocks; D. Communicate between coroutines through channels;Copy the code
Answer: the AD
53, What is true about loop statements
A. Loop statements support both the for keyword and while and do-while; B. The basic usage method of the keyword for is no different from that in C/C++; C. The for loop supports continue and break to control the loop, but it provides a more advanced break that allows you to choose which loop to break; D. the for loop does not support multiple comma separated assignments. Multiple variables must be initialized using parallel assignments.Copy the code
Answer: the CD
In C: Golang, goto statements can be unconditionally moved to the line specified in the procedure, and are usually used in conjunction with conditional statements. Can be used to achieve conditional transfer, constitute a cycle, jump out of the cycle body and other functions. Such as:
func main(a) { for a:=0; a<5; a++{ fmt.Println(a)if a>3{ goto Loop } } Loop: // put it after for fmt.Println("test")}Copy the code
The D: for statement performs variable balance initialization
for i, j := 0.5; i < j; i, j = i+1, j- 1 { fmt.Println("hhh")}Copy the code
54. What does the following code output?
func main(a) {
i := 1
s := []string{"A"."B"."C"}
i, s[i- 1] = 2."Z"
fmt.Printf("s: %v \n", s)
}
Copy the code
S: [Z B C]
Analytic: golang operator precedence: (+, -) > (=, + =, = =, *, /, % = =, > =, <, < =, & = ^ =, | =)
55, The following statement is true about the switch statement
A. Conditional expressions must be constants or integers. B. a singlecaseIn, multiple result options can appear; C. the need to usebreakTo explicitly exit onecase; D. only incaseTo explicitly addfallthroughKeyword will continue to execute immediately after the next onecase;Copy the code
Answer: the BD
Switch /case is an expression (i.e., a constant, a variable, or a function with a return); Error A does not require A break to exit A case explicitly
56, The following Add functions are defined correctly:
func Test54(t *testing.T) {
var a Integer = 1
var b Integer = 2
var i interface{} = &a
sum := i.(*Integer).Add(b)
fmt.Println(sum)
}
A.
type Integer int
func (a Integer) Add(b Integer) Integer {
return a + b
}
B.
type Integer int
func (a Integer) Add(b *Integer) Integer {
return a + *b
}
C.
type Integer int
func (a *Integer) Add(b Integer) Integer {
return *a + b
}
D.
type Integer int
func (a *Integer) Add(b *Integer) Integer {
return *a + *b
}
Copy the code
Answer: AC
The Add() function should have an Integer parameter
57, What is the wrong way to assign a bool to b?
A. b = true
B. b = 1
C. b = bool(1)
D. b = (1= =2)
Copy the code
Answer: the BC
Bool (1) bool(1); bool(1); bool(1)
58, The following statement is correct about the increment and decrement of a variable:
A
i := 1
i++
B
i := 1
j = i++
C
i := 1
++i
D
i := 1
i--
Copy the code
Answer: the AD
Golang does not have the expression ++ I or — I. The new variable j in B should be declared and initialized with :=
59, About the GetPodAction definition, the following assignment is correct
type Fragment interface {
Exec(transInfo *TransInfo) error
}
type GetPodAction struct{}func (g GetPodAction) Exec(transInfo *TransInfo) error{...return nil
}
A. var fragment Fragment = new(GetPodAction)
B. var fragment Fragment = GetPodAction
C. var fragment Fragment = &GetPodAction{}
D. var fragment Fragment = GetPodAction{}
Copy the code
Answer: the ACD
60, The following is true about the initialization of integer slices
A. s := make([]int)
B. s := make([]int.0)
C. s := make([]int.5.10)
D. s := []int{1.2.3.4.5}
Copy the code
Answer: the BCD
The length must be specified when a slice is initialized using the built-in make() method
Does the following code raise an exception
func main(a) {
runtime.GOMAXPROCS(1)
intChan := make(chan int.1)
stringChan := make(chan string.1)
intChan <- 1
stringChan <- "hello"
select {
case value := <-intChan:
fmt.Println(value)
case value := <-stringChan:
panic(value)
}
}
Copy the code
Answer: Maybe, maybe not
If both chan’s and CHAN’s cases match, the select will randomly select an available channel for sending and receiving operations
62. What is true about a channel
A. give AnilChannel sends data, causing a permanent blocknilA channel receives data and blocks permanently C. Sends data to a closed channelpanicD. Receives data from a closed channel and returns a zero value if the buffer is emptyCopy the code
Answer: the ABCD
Just play with your life
What is wrong with the following code:
const i = 100
var j = 123
func main(a) {
fmt.Println(&j, j)
fmt.Println(&i, i)
}
Copy the code
答案 : cannot take the address of I
In golang, constants cannot be addressed
64. What does the following code output?
func main(a) {
x := []string{"a"."b"."c"}
for v := range x {
fmt.Print(v)
}
}
Copy the code
Answer: 012
When x is map, the first value is key, and the second value is value
65. What is true about unbuffered and buffered channels?
A. The default buffer for unbuffered channels is1The channel; B. Unbuffered channels and buffered channels are synchronized; C. Unbuffered channels and buffered channels are asynchronous; D. Unbuffered channels are synchronous, while buffered channels are asynchronous.Copy the code
Answer: D
66. What does the following code output?
func Foo(x interface{}) {
if x == nil {
fmt.Println("empty interface")
return
}
fmt.Println("non-empty interface")}func main(a) {
var x *int = nil
Foo(x)
}
Copy the code
Answer: non-empty interface
The interface type value is nil if and only if both the dynamic type and dynamic type are nil. The dynamic type of x here is *int, so x is not nil
67. What is true about the select mechanism
A. selectMechanism to handle asynchronous I/O problems; B.selectOne of the biggest limitations of mechanics is that eachcaseThe statement must contain an IO operation; C. Golang is supported at the language levelselectKey words; D.selectThe usage of keywords andswitchStatements are very similar, followed by a judgment condition;Copy the code
Answer: ABC
Select (select) from (select); The use of select is very similar to that of switch, in that select starts a new selection block, and each selection condition is described by a case statement. Select has more restrictions than switch statements that can select any condition that can be used for equality comparison. The biggest restriction is that each case statement must have an IO operation, specifically, a channel-oriented IO operation.
What’s wrong with the following code
func Stop(stop <-chan bool) {
close(stop)
}
func main(a) {
c := make(chan bool)
Stop(c)
}
Copy the code
Invalid operation: close(stop) (cannot close receive-only channel)
A directed channel cannot be closed
69. What does the following code output
func main(a) {
var x = []int{2: 2.3.0: 1}
fmt.Println(x)
}
Copy the code
Answer: [1, 0, 2, 3]
Analysis: Slice initialization characteristics are as follows:
var x = []int{2: 2.3.0: 1.1} // [1 1 2 3] var x = []int{2: 2.3.0: 1.4:4} // [1 0 2 3 4] var x = []int{2: 2.3.0: 1.5:4} // [1 0 2 3 0 4] Copy the code
70. What does the following code output
func incr(p *int) int {
*p++
return *p
}
func main(a) {
v := 1
incr(&v)
fmt.Println(v)
}
Copy the code
Answer: 2
71. What does the following code output
func main(a) {
var a = []int{1.2.3.4.5}
var r = make([]int.0)
for i, v := range a {
if i == 0 {
a = append(a, 6.7)
}
r = append(r, v)
}
fmt.Println(r)
}
Copy the code
Answer: [1, 2, 3, 4, 5]
The number of times the object is copied depends on the value of the copy. The copy value is not affected by the change of the length of the object during the loop
What’s wrong with the following code
func main(a) {
var s []int
s = append(s,1)
var m map[string]int
m["one"] = 1
}
Copy the code
Panic: Assignment to entry in nil map
The slice declaration can be used, but the map needs to be initialized with the make function before it can be assigned
73. What does this code output
func main(a) {
fmt.Println("1")
defer fmt.Println("in main")
defer func(a) {
fmt.Println("3")
}()
fmt.Println("2")
defer func(a) {
defer func(a) {
panic("panic again and again")
}()
panic("panic again")
}()
panic("panic once")}Copy the code
1 2 3 in main panic: panic once panic: panic again panic: panic again and again
When the coroutine encounters Panic, it iterates through the linked list of defer from the coroutine and executes defer. During the process of defer, panic will be stopped if recover is encountered, and we will return to recover and continue to execute. If recover is not encountered, after iterating through the linked list of defer from this coroutine, panic information is thrown to stderr. Please refer to the article for details about how to use the potholes in defer
Build a foundation with you. See you next time