Golang wrong problem set

Source: Internet
Author: User

This document is the go language of those pits three.

Do not make any assumptions about the timing of go concurrency function execution

Take a look at the following:

1import (2 "FMT" 3 "Runtime" 4 "Time" 5) 6func main () {7names: = []string{"Lily", "Yoyo", "Cersei", "Rose", "Annei"}8for_, name : = Range Names{9go func () {10fmt. PRINTLN (name) one} () 12}13runtime. Gomaxprocs (1) 14runtime. Gosched () 15}

What is the output, please?

Answer:

1annei2annei3annei4annei5annei

Why is it? Is it a little surprised?

The output is "Annei", and "Annei" is the last element of "names", then the program prints out the value of the last element, and name is an external value for the anonymous function. Therefore, we can make an inference: Although each loop is enabled for a process, but these are references to the external variables, when the process is created, and then perform the printing action, the value of the name is not known to be what, because the main function of the process is also running, we parallel, But because the names array length is too small, when the process is created, the main function loop is already over, so all that is printed is the last element "Annei" that traverses the names.

How to prove the above inference?

In fact, it is very simple, after each cycle, pause for a period of time, waiting for the co-process to print the current name.

1import (2 "FMT" 3 "Runtime" 4 "Time" 5) 6func main () {7names: = []string{"Lily", "Yoyo", "Cersei", "Rose", "Annei"}8for_, name : = Range Names{9go func () {10fmt. PRINTLN (name) one} () 12time. Sleep (time. Second) 13}14runtime. Gomaxprocs (1) 15runtime. Gosched () 16}

Printing results:

1lily2yoyo3cersei4rose5annei

We come to the conclusion that we should not make any assumptions about the timing of the "Go function" unless you can indeed make the assumption that it is an absolute fact.

Suppose that a method on a T-type has both a T-type and a t-pointer-type, then the T-Receiver can not be called on a T-value that cannot be addressed

Please look at the code, can you compile and pass it?

1import (2 "FMT" 3) 4type Lili struct{5name string6}7func (Lili *lili) Fmtpointer () {8fmt. Println ("Poniter") 9}10func (Lili Lili) fmtreference () {11fmt. PRINTLN ("reference") 12}13func main () {14li: = Lili{}15li.fmtpointer () 16}

Answer:

1 can be properly compiled and output "Poniter"

Feel a bit surprised, please continue to look at the following code, how can compile pass?

1import (2 "FMT" 3) 4type Lili struct{5name string6}7func (Lili *lili) Fmtpointer () {8fmt. Println ("Poniter") 9}10func (Lili Lili) fmtreference () {11fmt. PRINTLN ("reference") 12}13func main () {14lili{}.fmtpointer () 15}

Answer:

1 cannot be compiled through. 2 "Cannot call pointer method on Lili literal" 3 "cannot take the Addressoflili literal"

Isn't it a little strange? What is this for? In fact, in the first code example, the main function of the "Li" is a variable, Li, although the type Lili, but Li is addressable, the &li type is Lili, so you can call the Lili method.

An interface that contains a nil pointer is not a nil interface

Please look at the following code to return what

1import (2 "bytes" 3 "FMT" 4 "IO" 5) 6constdebug =true7func Main () {8varbuf *bytes. Buffer9ifdebug{10buf =new (bytes. Buffer) 11}12f (BUF) 13}14func f (out IO. Writer) {15ifout! = nil{16fmt. Println ("surprise!") 17}18}

The answer is output: surprise.

OK, let's turn the debug switch off, and debug the value to False. So what does it output? is not anything output?

1import (2 "bytes" 3 "FMT" 4 "IO" 5) 6constdebug =false7func Main () {8varbuf *bytes. Buffer9ifdebug{10buf =new (bytes. Buffer) 11}12f (BUF) 13}14func f (out IO. Writer) {15ifout! = nil{16fmt. Println ("surprise!") 17}18}

The answer is: still output surprise.

What is this for?

This involves a concept, which is about the interface value. Conceptually, the value of an interface is divided into two parts: a type, a part of the value of the type, and they are called: Dynamic type and dynamic value, respectively. The type system is for a compiled language, and the type is the concept of the compile period, so the type is not a value.

In the preceding code, an *bytes is assigned to the out parameter of the F function. A null pointer to buffer, so the dynamic value of out is nil. Its dynamic type is however bytes. Buffer, meaning: "A non-nil interface containing a nil pointer", so the result of "Out!=nil" is still true.

However, for direct bytes. This issue does not occur with the null space of the buffer type.

1import (2 "bytes" 3 "FMT" 4) 5func main () {6varbuf *bytes. Buffer7ifbuf = = Nil{8fmt. Println ("Right") 9}10}

or output: Right

The above pits appear only when the interface pointer passes in the function's interface parameter.

It is also very convenient to change the *bytes. It would be nice to change the buffer to Io.writer.

1import (2 "bytes" 3 "FMT" 4 "IO" 5) 6constdebug =false7func Main () {8varbuf io. writer//originally was Var buf *bytes. Buffer9ifdebug{10buf =new (bytes. Buffer) 11}12f (BUF) 13}14func f (out IO. Writer) {15ifout! = nil{16fmt. Println ("surprise!") 17}18}

When you convert a map to a JSON string, the order in the JSON string is independent of the order of the map assignment

Please look at the following code, what output? If it is a JSON string, what is the order of key in the JSON string?

1func Main () {2params: = Make (map[string]string) 3params["id"] = "1" 4params["id1"] = "3" 5params["Controller"] = "sections "6data, _: = json. Marshal (params) 7fmt. Println (String (data)) 8}

Answer: Output {"Controller": "sections", "id": "1", "ID1": "3"}

Using the JSON conversion package transform from Golang, the order of keys in the map is changed to alphabetical order instead of the map's order of assignment. Map this structure even when using the for range traversal, where the key is also unordered, can be understood as map is an unordered structure, and PHP in the array to distinguish

JSON deserializes a number into a value of type interface{}, by default resolves to float64 type

Please look at the following program, the program wants to output JSON data integer ID plus 3 value, will the program error?

1func Main () {2jsonStr: = ' {' id ': 1058, ' name ': ' Ryugou '} ' 3varjsonData Map[string]interface{}4json. Unmarshal ([]byte (JSONSTR), &jsondata) 5sum: = jsondata["id"]. (int) +36fmt. PRINTLN (SUM) 7}

The answer is an error, the output is:

Panic:interfaceconversion:interface{}isfloat64, Notint

1 When you use Golang to parse JSON-formatted data, if you receive data in interface{}, the following rules are used for parsing:

Bool,forjson Booleansfloat64,forjson Numbersstring,forjson Strings[]interface{},forjson arraysmap[string]interface {},forjson Objectsnilforjsonnull

1 should read:

2go

3func Main () {

4 Jsonstr: = {"id": 1058, "name": "Ryugou"}

5 var jsondata map[string]interface{}

6 JSON. Unmarshal ([]byte (JSONSTR), &jsondata)

7 sum: = Int (jsondata["id"]. ( float64)) + 3

8 FMT. PRINTLN (SUM)

9}

>>>> Read the full text

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.