The third Go Q&A summary, in August 2019, is about 12 q&a summaries. The addresses of the first two are as follows:

Go answer summary 2

Most of the problems come from Zhihu and segmentfault. This month’s question comes from StackOverflow. My English is so-so. I can read and translate, but I need to work on my writing. Although this answer did not get any approval, but can be adopted by the subject, I am still very honored.

Recently, I found that my answers are often included in the weekly magazine of Go Language Chinese. If you are interested in Go, you can follow the official account of Go Language Chinese, which is very rich in content. Excellent articles about Go will be pushed every day.

Start the text!

dynamodbattribute.UnmarshalMap canges the type of my variable to map[string]interface{}

To put stackOverflow’s answer at the top of the heap, the questions aren’t too hard, but there are plenty of good questions on StackOverflow, especially on the first try.

The goal is to convert the map type to a struct type. To simplify the problem slightly, you want to convert map[string]interface{} to user by writing it like this.

package main

import "fmt"

type User struct {
	Name string
}

func Item(a) interface{} {
	return User{}
}

func ItemMap(s map[string]interface{}, item *interface{}) {
	*item = s
}

func main(a) {
	m := Item()
	fmt.Printf("%T\n", m)
	fmt.Printf("%v\n", m)

	s := map[string]interface{} {"Name": "poloxue",
	}
	ItemMap(s, &m)

	fmt.Printf("%T\n", m)
	fmt.Printf("%v\n", m)
}
Copy the code

First, we create a variable of type User through the Item() method, but it returns type interface{}, so the m in main is derived by type, which is type interface{}, Assigning the map[string]interface{} variable to the address of m in the ItemMap function does not cause any problems, because the underlying type of m is User, but this layer is not checked. After a part of the assignment, Map [string]interface{} is not a complete map[string]interface{}.

It seems that map and struct conversions are still common requirements, and last month’s q&A summary had similar problems. Again, the MapStructure package is recommended.

Go source raceenable is what to do, can answer one or two!

Go is a language with built-in concurrency support. A common problem with concurrency is race conditions. Go provides a special tool to detect this problem. This raceEnable representation in the Go source code means even if raceEnable is enabled or not.

I translated an article about go race, visit the go translation race detector race.

In Golang, runtime.Caller(skip), why do I keep compiler variables?

Runtine.caller can be used to check the call stack information, which can be used to keep the source file information at compile time.

But real projects deploy executables, not source files, and paths are paths to executables. How do you get it? Look at the answer!

Another reminder, because many friends have developed an interpreted language thinking, often by go run to execute the source code, and then get the executable file path, but ultimately get a really unreadable path. This question is also introduced in the answer.

How does Golang reuse mysql connections?

The standard library Database/SQL in Golang already provides a common implementation of database management, which also involves mysql connection reuse.

The main question is why the reuse effect is not achieved.

Connection reuse has an important premise is to remember the release of resources after the end of use, otherwise it will always be in the occupied state, as to what circumstances will lead to connection reuse, check answer!

There is a very systematic introduction to the use of DATABASE/SQL in Go.

The Goroutine is abnormal

It’s a little bit more complicated. The reason for the exception is that the channel sender waits too long to send, which leads to the exception. The core idea of the parsing problem is to add a buffer between the sender and the receiver. Whatever the sender sends, the message is first received into the buffer and then sent out of the buffer when there is an idle receiver.

The main problem is realized by using chan’s own buffer, creating chan with a buffer size of 50. Of course, a more flexible approach is to implement your own buffer. In addition, the scene of the topic is crawler, so the size of buffer may be relatively high, and external services may be properly considered.

Does go reflect get the names of private methods of types defined by other files in the same package?

First, to be clear, reflection in Go does not see private methods of types. If you want to do this, you can only define a method as an exportable method. But private methods have the advantage of being unavailable to the outside world. Is it possible to make methods publicly exportable to make them unusable?

Check out my answers!

How does Beego’s cache translate to a structure?

Beego cache storage and access issues, very simple, nothing to say!

How does select listening work in go?

The core of the problem is not how select works, but the use of the timer in Go. The following is the core code of the problem.

for {
	select {
		case num := <-ch:
			fmt.Println("get num is ", num)
		case <-time.After(2 * time.Second):
			fmt.Println("time's up!!!")
			//quit <- true}}} ()Copy the code

Why is the case of the timer never executed? This is because time.After creates the chan on each loop, before timing chan no longer listens.

I began to think that this method was quite suitable for handling the situation of timeout. A friend reminded me that there was a risk of leakage. Specific reasons, read the answer to understand!

In Golang’s design, why can’t you use switch to implement select?

Select is a special name for multiplexing. Switch is a branch structure, but it is not easy to understand. I feel that a new keyword will be better understood independently.

Go language struct has a function of the exponential example

The main problem is to introduce the problem of struct containing function members in Go from shallow to deep. I don’t think I’ve written much either, but it hasn’t been taken up by the subject, only one comment.

Is golang compiler available in 32 and 64 versions?

It’s definitely divided, but don’t worry, the go command is already packaged, and it selects different underlying commands depending on the platform.

In the PKG directory of the go installation directory is the Tools directory, which contains the commands actually used to compile links, such as my Mac Pro, PKG /tool/darwin_amd64/ you can find the commands compile and link that the go compilation link actually calls. In darwin_AMD64, DRAwin stands for operating system, and AMD64 is the system architecture.

When you execute go env, you’ll find an environment variable called GOTOOLDIR, which is the directory for tools that are relevant to our platform. Here’s what I get on my Mac:

GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
Copy the code

How does the re match the last page number?

The question is how to parse HTML.

<ul id="pages">
<li><a href="xxx1">1</a></li>
<li><a href="xxx2">2</a></li>
<li><a href="xxx3">3</a></li>
</ul>
Copy the code

For this type of problem, regular matching is not recommended. Instead, try goQuery, a jquery library that parses HTML content in a very convenient way. Of course, the re implementation is also explained in the answer, but the code looks less readable.

This month’s answer is concluded, if you find any improper content, welcome criticism and correction, thank you very much.


Welcome to follow my personal wechat public number.