Double curly braces in structures when used in Decode(&struct{}{})

王林
Release: 2024-02-15 12:50:09
forward
546 people have browsed it

在 Decode(&struct{}{}) 中使用时结构中的双大括号

In PHP, we can use Decode(&struct{}{}) to decode a structure. However, there is a special case when we use a structure in the Decode function, we need to use double curly braces in the structure. This usage can be confusing, so I'll explain it in detail here. When using a structure in the Decode function, the double curly braces are used to indicate the initialization of the structure. In this way, we can define and initialize a structure in one statement, making the code more concise and easier to understand. Therefore, remember to pay attention to the use of double braces when using structures in the Decode function!

Question content

I have this function in some code. What are the double braces in the struct that help make sure it's not two JSONs? How does it work?

func readJSON(w http.ResponseWriter,r *http.Request,data interface{}) error {
    maxBytes := 1024 * 1024 
    r.Body = http.MaxBytesReader(w,r.Body,int64(maxBytes))
    dec := json.NewDecoder(r.Body)
    dec.DisallowUnknownFields()
    err := dec.Decode(data)

    if err != nil {
        return err
    }

    err = dec.Decode(&struct{}{})
    if err != io.EOF {
        return errors.New("Body must Only contain 1 json ")
    }
    
    return nil
}
Copy after login

Solution

Let’s break it down:

  • struct{} is a type: a structure without fields.
  • struct{}{} is a literal value: a new instance of the above type.
  • &struct{}{} is a pointer to the literal value above.

By trying to decode the JSON a second time, it confirms that the body does not have a second JSON document after the first one, for example:

{
  "foo": "bar"
}
{
  "foo": "qux"
}
Copy after login

The above is the detailed content of Double curly braces in structures when used in Decode(&struct{}{}). For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template