Subject indexing

  • How do I declare multiple types of variables at once?
  • What are the reference types in Go?
  • Q: what are the “static type” and “dynamic type” declarations of variables?
  • The following variables are correctly assigned to ().
  • The difference between “=” and “:=”?
  • Q: What are the types in Go where zero is nil?
  • Question: Can 2 nil be unequal?
  • Q: What types of comparison are not supported in Go?
  • Which types does the built-in make() function apply to?
  • What types of cap() are applicable to the built-in function?
  • What is the difference between new() and make()?
  • Question: Can the following program compile? If yes, what is the result of the run?
  • Write the result according to the following code.
  • How do I print the type of a variable in Go?
  • What is the difference between Printf(), Sprintf() and Fprintf()?
  • What is true about init()?
  • When is the init() function executed?
  • What is the result of the following program?
  • Q: What is the result of the following program?
  • Add() = Add()
  • Sum() = Sum(); Sum() = Sum()
  • What is the problem with the following program, please explain the reason?


How do I declare multiple types of variables at once?

Their thinking

Variable declaration

  • Single variable declaration:
    • Var Variable name Variable typeA statement, such as:var name string;
    • Var Variable name = variable valueDeclare initialization, as in:var name = "xx"Value types are type checked at compile time.
    • := declaration, such as: name := “xx”,, compile time will check the value type;
  • Declarations of multiple variables:
    • Var Variable name 1, variable name 2... Variable types
    • Variable value 1, variable value 2… Var x, y = 5, 6;
    • X, y:= 5, “name”;
    • Var (name of a variable and type of a variable), such as var (x int y string), is used to declare global variables.
  • Multiple variable types:
    • Variable value 1, variable value 2… Var x, y = 5, 6;
    • X, y:= 5, “name”;
    • Var (name of a variable and type of a variable), such as var (x int y string), is used to declare global variables.

answer

var (
    x int
    y string
)

x, y := 1."name"
Copy the code


What are the reference types in Go?

Their thinking

Reference Type = reference type

Reference Type: A data type represented by a reference (similar to a pointer) to the actual value of the type.

In Go, a reference type can be easily identified by making () to initialize it.

answer

Slice, map, channelCopy the code


Q: what are the “static type” and “dynamic type” declarations of variables?

Their thinking

Static type, dynamic type

Static typing: A program can specify variable types at compile time.

Dynamic typing: Variable types can only be derived at runtime.

All of the normal data types in Go can be identified at compile time, except for mutable types like interface{}, which can be inferred only when the program is running and given values.

answer

// Dynamic type declaration
var i interface{}

Static type declaration
var num int
Copy the code


The following variables are correctly assigned to ().

A. var x = nil

B. var x interface{} = nil

C. var x string = nil

D. var x error = nil

Their thinking

C. nil D. nil

  • Although nil is used as A zero for multiple types, it must be used with an explicit variable type, so option A is excluded

  • Nil assignment types are supported: pointer, slice, map, channel, interface, error, so option C is excluded

Answer:B, D


The difference between “=” and “:=”?

Their thinking

We know that the biggest difference between = and = is that we can not only declare variables, but also assign values

Answer:

:= declare + assign, = assign only


Q: What are the types in Go where zero is nil?

Their thinking

Zero value types: pointer, slice, map, channel, interface, error

answer

Pointer, slice, map, channel, interface, error


Question: Can 2 nil be unequal?

Their thinking

Why does my nil error value not equal nil? .

First we need to know that nil is a [pre-declared identifier], not a [keyword]. Nil itself has no fixed type. When used, nil provides information so that the compiler can infer the expected type of nil with an indeterminate type.

package main

import "fmt"

func main(a) {
    // Two nil values, different types than the output false
    fmt.Printf("[interface == int]=>%v", (interface({})nil(*) = =int) (nil))

    // ------------- -------------
    // Use nil as a variable, so it is not a keyword
    nil: ="hello world"
    fmt.Println(nil)

    // ------------- -------------
    var p *int = nil
    var i interface{} = p
    fmt.Println(i == p)     // true
    fmt.Println(p == nil)   // true
    fmt.Println(i == nil)   // false
Copy the code

Answer: Maybe


Q: What types of comparison are not supported in Go?

Their thinking

Comparison operators

Refer to the official documentation for an explanation in the comparison operator.

Comparable type Non-comparable type
Bool Slice
Int Map
Float function
struct Fields containing the comparable type == struct Contains fields of the == non-comparable type ==
ArrayAn array type with the == comparable element == ArrayAn array type with == non-comparable element ==
Complex
String
Pointer
Channel
Interface

answer

Slice, Map, Function, Struct(fields containing non-comparable types), Array(Array types with non-comparable elements)


Which types does the built-in make() function apply to?

Their thinking

The built-in function make()

The make() function is mainly used to initialize variables and allocate specified memory. Make () only applies to slice, map, and channel, which must be initialized before being used.

answer

Slice, Map, Chan


What types of cap() are applicable to the built-in function?

Their thinking

The built-in function cap()

Refer to the official CAP () documentation

Cap () is one of the built-in functions that returns its corresponding capacity based on the passed variable.

  • Array: The number of elements of the returned array andlen()Returns the same value, i.elen(v) == cap(v);
  • ; Pointer to array: a Pointer to an array that essentially evaluates an array;
  • Slice: The maximum length that a Slice can reach when re-slicing;
  • Channel: The buffer capacity of the channel, in units of elements.

answer

Array, Slice, Chan


What is the difference between new() and make()?

Their thinking

New (), make()

Two built-in functions, both primarily used to create types and allocate memory (on the heap).

Function definition:

  • New () : func new(Type) *Type, returns a pointer;
  • Make () : func make(Type, size IntegerType) Type

Function:

  • New (): allocates a memory space based on the type passed in and returns a pointer to that memory space;
  • make()Is used to initialize built-in data structuresslice,map,channel;

answer

Make () is only used for initialization of slice, map, and channel and returns a non-zero value, while new() allocates a memory space for the type and returns a pointer to that memory.


Question: Can the following program compile? If yes, what is the result of the run?

package main

import "fmt"

func main(a) {
    l := new([]int)
    l = append(l, 1)
    fmt.Println(l)
}
Copy the code

Their thinking

New (), append()

New () is a pointer to a slice of memory and returns the address that points to the slice.

Func append(slice []Type, elems… Type) []Type

The first argument to this function is of Type []Type, not a pointer Type.

first argument to append must be slice; have *[]int
Copy the code

answer

Compile failed


Write the result according to the following code.

package main

import "fmt"

func main(a) {
    s := make([]int.5)
    s = append(s, 1.2.3)
    fmt.Println(s)
}
Copy the code

Their thinking

The examination site: make ()

Make uses default values when declaring slices

answer

[0 0 0 0 1 2 3]Copy the code


How do I print the type of a variable in Go?

Their thinking

Test point: Format output

Refer to the format specifier

answer

a := 1
fmt.Printf("%T", a)
Copy the code


What is the difference between Printf(), Sprintf() and Fprintf()?

Their thinking

answer

Both output well-formed strings, but the output target is different:

  • Printf() : Prints the format string to standard output (usually screen, redirected)
  • Printf() : is associated with the standard output file (stdout). Fprintf does not have this limitation
  • Sprintf() : prints the format string to the specified string, so the argument is one char* longer than printf. That’s the destination string address
  • Fprintf() : prints the format string to the specified FILE device, so the parameter pen printf has a FILE pointer FILE*. Mainly used for file operations. Fprintf() formats output to a stream, usually to a file.


What is true about init()?

A. A package can contain multiple init functions

B. During program compilation, run the init function of the imported package first and then the init function in the package

C. The main package cannot contain init functions

D. init can be called by other functions

Their thinking

The order in which init() is executed

In the package import process, the execution sequence of init() function is shown as follows:

Main functions:

Main features:

  • Init () is automatically executed before main() and cannot be called by other functions;
  • Init () has no input parameters and no return value;
  • Each package can have multiple init() functions;
  • Each source file of a package can also have multiple init() functions;
  • The order in which the init() function is executed depends on the package import dependencies;

answer

A and BCopy the code


When is the init() function executed?

Their thinking

The init() function is part of the Go program’s initialization. The Go program initializes each imported package before the Main function, and the Runtime initializes each imported package, not in the top-down import order, but in terms of resolved dependencies. Packages without dependencies are initialized first.

Each package initializes its scoped constants and variables (constants take precedence over variables), and then executes the package’s init() function. The same package, or even the same source file, can have multiple init() functions. The init() function has no input arguments or return values and cannot be called by other functions. The order in which multiple init() functions are executed in the same package is not guaranteed.

Go program execution sequence:

Import () -- > const() -- > var() -- > init() -- > main()Copy the code

For details, see the following example:

answer

The Go program initialization precedes the main() function.Copy the code


What is the result of the following program?

package main

import "fmt"

const (
    a = iota
    b
    c = "name"
    d
    e = iota
)

func main(a) {
    fmt.Println(a, b, c, d, e)
}
Copy the code

Their thinking

The examination site: iota

  • iotaReset to 0 when the const keyword is present
  • Const declares each new row in the blockiotaValue on the 1

Iota represents the row index of a const declaration block (subscripts start at 0)

answer

0 1 name name 4
Copy the code


Q: What is the result of the following program?

defer fmt.Println(9)

fmt.Println(0)

defer fmt.Println(8)

fmt.Println(1)

defer func(a) {
    defer fmt.Println(7)
    fmt.Println(3)
    defer func(a) {
        fmt.Println(5)
        fmt.Println(6)
    }()
    fmt.Println(4)
}()

fmt.Println(2)
Copy the code

Their thinking

The examination site: defer

Defer is a keyword for delayed function calls, and its main purpose is to defer a function call, which will not be executed immediately. It will be pushed onto a deferred call stack maintained by the current coroutine.

The order of defer execution is FILO (first in, last out).

answer

0, 1, 2, 3, 4, 5, 6, 7, 8, 9Copy the code


Add() = Add()

Add() function implementation code is as follows:

func Add(args ...int) int {
    sum := 0
    for _, arg := range args {
        sum += arg
    }
    return sum
}
Copy the code

A. Add(1, 2, 3)

B. Add([]int{1, 2, 3})

C. Add([]int{1, 2, 3}…)

D. Add(1, 2)

Their thinking

answer

A, C, DCopy the code


Sum() = Sum(); Sum() = Sum()

package main

import "fmt"

func main(a) {
    var a, b int = 1.2
    var i interface{} = &a
    sum := i.(*int).Sum(b)
    fmt.Println(sum)
}
Copy the code

Their thinking

answer

type Integer int

func (i *Integer) Add(v Integer) Integer {
    return *i + v
}
Copy the code


What is the problem with the following program, please explain the reason?

package main

type student struct {
	Name string
	Age  int
}

func main(a) {

    m := make(map[string]*student)

    stus := []student{
        {Name: "zhou", Age: 24},
        {Name: "li", Age: 23},
        {Name: "wang", Age: 22}},for _, stu := range stus {
        m[stu.Name] = &stu
    }
}
Copy the code

Their thinking

For… range

Foreach uses a copy of the variable, so when the loop is fetched, it actually points to the same pointer, resulting in the problem of obtaining the same value.

For the purposes of this case, you might not notice this detail when you look at the program, but in fact stu is still pointing to the same address after iterating through it.

answer

The “for” assignment is a bit of a problem. The “for” assignment is a copy of the “for” assignment. The “for” assignment is a copy of the “for” assignment.