Golang interview: golang basic grammar (1)


title: golang basic grammar (1)
auther: Russshare
toc: true
date: 2021-07-13 18:56:29
tags: [golang, interview]
categories: golang interview

I have been busy with interviews recently, so I will update this to the blog for easy viewing at any time. If something is wrong, please pay attention to inform me. Most of the content comes from the articles of the seniors, because I forgot to copy the link when I was taking notes. If you know anything, please add it. Will add link.

  • 1. Basic grammar

    • 01 What is the difference between = and :=?

      • = is a simple assignment
        : = has the function of declaring variables
    • 02 map

      • 01. How to read the map sequentially

        • Map cannot be read in sequence because it is unordered. If you want to read in order, the first problem to solve is to make the key into order, so you can put the key into the slice, sort the slice, and traverse the slice , get the value by key.
      • 02 How to judge whether a certain key is contained in the map?

    • 03 In go language, what is the difference between new and make?

      • Action object

        • make can only be used for slice, chan, map to initialize these objects
        • new is used for any type of golang custom type and built-in data type
      • Semantics

        • make(T,args) initialize built-in data structures (slice, chan, map)
        • new(T) allocates a piece of zero-value memory space according to the type passed in, and returns the pointer value *T pointing to this piece of memory space, and creates a pointer to the object explicitly without using the &T pair to get the address of the object .
    • 04 slice and array slice

      • array

        • (1). Array
          An array is a sequence with fixed length and zero or more elements of the same data type.

        The length of the array is part of the array type, so [3]int and [4]int are two different array types.

        The size of the array needs to be specified, if not specified, the size will be automatically calculated according to the initialization, and cannot be changed;

        Arrays are passed by value;

        An array is a built-in (build-in) type, which is a collection of data of the same type. It is a value type, and the element value is accessed through a subscript index starting from 0.

        The length is fixed after initialization and cannot be modified. When passed as a method parameter will make a copy of the array instead of referencing the same pointer. The length of an array is also part of its type, and its length can be obtained through the built-in function len(array).

          数组定义:var array [10]int
          var array = [5]int{1,2,3,4,5}
        
          	- 切片
        
          		- 切片表示一个拥有相同类型元素的可变长度的序列。
        

        A slice is a lightweight data structure that has three properties: pointer, length, and capacity.

        Slices do not need to specify a size;

        Slicing is pass-by-address;

        Slices can be initialized by an array, or by the built-in function make(). When initializing, len=cap, when adding elements, if the capacity cap is insufficient, the capacity will be expanded by twice the len;

        Slice definition: var slice []type = make([]type, len)

      • slice, len, cap, sharing, expansion

        • len: the length of the slice, the access time complexity is O(1), and the bottom layer of go's slice is a reference to the array.
        • cap: The capacity of the slice, and the expansion is based on this value. The default expansion is 2 times, when the length reaches 1024, it will be 1.25 times.
        • Expansion: Every time the bottom layer of the slice is expanded, a new capacity memory space will be allocated first, and then the old array will be copied to the new memory space, because this operation is not concurrently safe. Therefore, if the append operation is performed concurrently, the old array in the memory read may be the same, which eventually leads to the loss of append data.
        • Sharing: The bottom layer of a slice is a reference to an array, so if two slices refer to the same array segment, a shared bottom layer array will be formed. When memory reallocation (such as expansion) occurs in sliec, the sharing will be isolated. See the following example for details:
    • 05 In the go language, what is the difference between Printf(), Sprintf(), and Fprintf() functions?

      • Print() is to output the format string to standard output (usually the screen, which can be redirected).
      • Printf() is associated with the standard output file (stdout), while Fprintf does not have this limitation.
      • Sprintf() is to output the format string to the specified string, so the parameter is one more char* than printf. That is the target string address.
      • Fprintf() is to output the format string to the specified file device, so the parameter pen printf has one more file pointer FILE*. Mainly used for file operations. Fprintf() is formatted output to a stream, usually to a file.
    • 06 Explain what the following command does?

      • go env: #Environment variables for viewing go

      • go run: # used to compile and run go source code files

      • go build: #Used to compile source code files, code packages, and dependent packages

      • go get: #Used to dynamically obtain remote code packages

      • go install: #Used to compile go files and install the compiled structure to the bin and pkg directories

      • go clean: #Used to clean up the working directory, delete the target files left over from compilation and installation

      • go version: #Used to view the version information of go

    • 07 There is no hidden this pointer in the go language. What does this sentence mean?

    • 08 int and int32

      • The Go language is a strongly typed language. Even if the underlying structure is the same, if the declared types are different, they must be cast. Type conversions may result in loss of precision. Therefore, the design principle of Go is that there is no implicit type conversion
    • 09 Talk about the main function of go language

      • The main function cannot take parameters
      •   main函数不能定义返回值
        
      •   main函数所在的包必须为main包
        
      •   main函数中可以使用flag包来获取和解析命令行参数
        
    • 10 Talk about the init function in go language?

      • (1), a package can contain multiple init functions
      • (2) When the program is compiled, first execute the init function of the imported package, and then execute the init function in this package
    • 11 Does Go allow multiple return values?

      • The Go language is the first to provide multiple return value functions revolutionaryly in the static development language camp.
    • 12 What are the reference types in go language?

      • Array slice, dictionary (map), channel (channel), interface (interface)
    • 13 Does Go have exception types?

      • there is err
    • 14 channel

      • In addition to adding Mutex locks in Golang, what other ways are there to safely read and write shared variables?

        • Goroutine in Golang can safely read and write shared variables through Channel
      • Are the sending and receiving of unbuffered Chan synchronous?

      • characteristic

        • A. Send data to a nil channel, causing permanent blocking
        • B. Receive data from a nil channel, causing forever blocking
        • C. Send data to a closed channel, causing a panic
        • D. Receive data from a closed channel, and return a zero value if the buffer is empty
        • E. Unbuffered channels are synchronous, while buffered channels are asynchronous
    • 15 How to concatenate strings efficiently

      • In the case of an existing string array, using strings.Join() can have better performance

      • In some occasions with high performance requirements, try to use buffer.WriteString() to obtain better performance

      • When performance requirements are not too high, use operators directly, the code is shorter and clearer, and better readability can be obtained

      • If you need to splice not only strings, but also other needs such as numbers, you can consider fmt.Sprintf()

    • 16 What is the rune type

      • //alias of int32, equivalent to int32 in almost all respects

      • //It is used to distinguish between character values ​​and integer values

      • byte is equivalent to uint8, commonly used to process ascii characters

      • rune is equivalent to int32, commonly used to deal with unicode or utf-8 characters

    • 17 Does Go support default or optional parameters?

      • Go language pursues explicit expression and avoids implicit, this design is especially evident in its object-oriented syntax

      • The language that does not support the default value is a tool. The syntax of go is simple and does not support anything, which is to prevent the tool from being abused.

    • 18 Execution order of defer

      • You only need to add the keyword defer before calling an ordinary function or method, and the syntax required by defer is completed.

      • When the defer statement is executed, the function following the defer will be delayed.

      • The function after defer will not be executed until the function containing the defer statement is executed.

      • Regardless of whether the function containing the defer statement ends normally through return, or ends abnormally due to panic.

      • You can execute multiple defer statements in a function, and their execution order is reverse to the declaration order.

      • Common scenarios for defer:

          • The defer statement is often used to handle pairs of operations, such as open, close, connect, disconnect, lock, release lock.
          • Through the defer mechanism, no matter how complex the function logic is, it can guarantee that resources will be released under any execution path.
          • The defer that releases resources should be directly followed by the statement that requests resources.
    • 19 What is the use of Go language tag?

      • tag can be understood as the annotation of the struct field, which can be used to define one or more attributes of the field. Frameworks/tools can obtain the attributes defined by a certain field through reflection, and take corresponding processing methods. tag enriches the semantics of the code and enhances flexibility. go with json string
    • 20 How to judge that two string slices (slice) are equal?

      • 1. In the go language, you can use reflection reflect.DeepEqual(a, b) to judge whether the two slices a and b are equal, but it is generally not recommended to do so, and using reflection will greatly affect performance.
      • 2. The usual method is as follows, traversing each element in the comparison slice (pay attention to dealing with out-of-bounds situations).
    • 21 When printing a string, the difference between %v and %+v

      • Both %v and %+v can be used to print the value of struct, the difference is that %v only prints the value of each field, and %+v also prints the name of each field.
      • But if the structure defines a String() method, both %v and %+v will call String() to override the default value.
    • 22 How to represent enumeration values ​​(enums) in Go language?

    • 23 Use of empty struct{}

      • Using an empty structure struct{} can save memory, and is generally used as a placeholder, indicating that a value is not needed here.

        • For example, when using a map to represent a collection, only focus on the key, and the value can use struct{} as a placeholder. If you use other types as placeholders, such as int and bool, it not only wastes memory, but also easily causes ambiguity.
        • Declares a struct containing only methods.
    • 24 interface instead of inheritance polymorphism

      • An interface type is an abstract type that does not expose the internal values ​​of the object it represents and the operation methods supported by the object. The interface will only show what it is used for by declaring methods (behaviors), without knowing what it is.

      • Go is not strictly an object-oriented programming language, understand the characteristics and programming ideas of Go's interface, polymorphism and inheritance

      • https://zhuanlan.zhihu.com/p/59749625

      • Interface is divided into two types 1. Empty interface 2. Interface with method

    • 25 Can go struct be compared?

      • A structure is comparable if all its member variables are comparable
      • If there are non-comparable member variables in the structure, the structure cannot be compared
      • Conversion between structures requires that they have exactly the same members (field name, field type, number of fields)
    • 26 What can select be used for

      • (1), the select mechanism is used to deal with asynchronous IO problems
      • (2), the biggest limitation of the select mechanism is that each case statement must be an IO operation
      • (3), golang supports the select keyword at the language level
    • 27 Does the JSON standard library treat nil slices and empty slices consistently?

      • First of all, the JSON standard library's handling of nil slices and empty slices is inconsistent.
    • 28 Explain what type of language the go language is? What are its features and what can it be used for?

        1. Static Strong Type 2. Compiled Type 3. Concurrent Type 4. Programming Language with Garbage Collection
    • 29 Explain what is the strong type in the go language? What does it do?

        1. Static Strong Type 2. Compiled Type 3. Concurrent Type 4. Programming Language with Garbage Collection
        • Static type: the type is determined at compile time, java/C/C++/golang
        • Dynamic typing: Python/PHP is determined at runtime
        • Strong type: The type is defined, and its type cannot be changed. However, in the C language, although a short is defined, it can still be used as a char, because the memory can be directly manipulated.
        • Weak type: Free conversion between types

Guess you like

Origin blog.csdn.net/weixin_45264425/article/details/132200012