有没有理由为什么bb.person被填满但a.Person没有?

时间:2017-11-04 18:56:58

标签: go

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "enigmaPaamelding";

    $conn = new mysqli($servername, $username, $password);

    // Create database
    $sql = "CREATE DATABASE enigmaPaamelding";
    if ($conn->query($sql) === TRUE) {
        echo "Database created successfully";
    } else {
        echo "Error creating database: " . $conn->error;
    }

   // sql to create table
   $sql = "CREATE TABLE BedriftPaameldinger (
   id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
   code VARCHAR(30) NOT NULL,
   name VARCHAR(30) NOT NULL,
   email VARCHAR(50),
   reg_date TIMESTAMP
   )";

结果:

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    First string `json:"name"`
}

type person struct {
    Last string `json:"name"`
}

type A struct {
    *Person `json:"person"`
}

func (a *A) UnmarshalJSON(b []byte) error {
    type alias A

    bb := struct {
        *person `json:"person"`
        *alias      
    }{
        alias: (*alias)(a),
    }

    if err := json.Unmarshal(b, &bb); err != nil {
        return err
    }

    fmt.Printf("%+v\n", bb.person)

    return nil
}

func main() {
    b := []byte(`{"person": {"name": "bob"}}`)
    a := &A{}

    if err := json.Unmarshal(b, a); err != nil {
        fmt.Println(err)
    }

    fmt.Printf("%+v\n", a.Person)
}

为什么bb.person和a.Person具有相同的struct标签但只填充了bb.person?我还没有找到合适的文件,但为什么会发生这种情况并保证永远都会发生呢?

https://play.golang.org/p/Fvo_hg3U6r

0 个答案:

没有答案